在 Windows 中更改 Python 3 中的“语言环境首选编码" [英] Changing the “locale preferred encoding” in Python 3 in Windows

查看:29
本文介绍了在 Windows 中更改 Python 3 中的“语言环境首选编码"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Python 3(最近从 Python 2 转换而来).我的代码通常在 Linux 上运行,但有时(不经常)在 Windows 上运行.根据 open(),如果未提供 encoding 参数,则文本文件的默认编码来自 locale.getpreferredencoding().对于我的项目,我希望这个默认值是 utf-8,无论它在什么操作系统上运行(目前,对于 Linux,它始终是 UTF-8,但不适用于 Windows).该项目有很多对 open() 的调用,我不想将 encoding='utf-8' 添加到所有调用中.因此,我想在 Windows 中更改语言环境的首选编码,正如 Python 3 所见.

I'm using Python 3 (recently switched from Python 2). My code usually runs on Linux but also sometimes (not often) on Windows. According to Python 3 documentation for open(), the default encoding for a text file is from locale.getpreferredencoding() if the encoding arg is not supplied. I want this default value to be utf-8 for a project of mine, no matter what OS it's running on (currently, it's always UTF-8 for Linux, but not for Windows). The project has many many calls to open() and I don't want to add encoding='utf-8' to all of them. Thus, I want to change the locale's preferred encoding in Windows, as Python 3 sees it.

我发现了一个以前的问题更改区域设置首选编码"",它有一个公认的答案,所以我以为我可以走了.但不幸的是,该答案中的建议命令及其第一条评论在 Windows 中都不适合我.具体来说,该接受的答案及其第一条评论建议运行 chcp 65001set PYTHONIOENCODING=UTF-8,我都试过了.请从我的 cmd 窗口查看下面的文字记录:

I found a previous question "Changing the "locale preferred encoding"", which has an accepted answer, so I thought I was good to go. But unfortunately, neither of the suggested commands in that answer and its first comment work for me in Windows. Specifically, that accepted answer and its first comment suggest running chcp 65001 and set PYTHONIOENCODING=UTF-8, and I've tried both. Please see transcript below from my cmd window:

> py -i
Python 3.4.3 ...
>>> f = open('foo.txt', 'w')
>>> f.encoding
'cp1252'
>>> exit()

> chcp 65001
Active code page: 65001

> py -i
Python 3.4.3 ...
>>> f = open('foo.txt', 'w')
>>> f.encoding
'cp1252'
>>> exit()

> set PYTHONIOENCODING=UTF-8

> py -i
Python 3.4.3 ...
>>> f = open('foo.txt', 'w')
>>> f.encoding
'cp1252'
>>> exit()

请注意,即使在两个建议的命令之后,我打开的文件的编码仍然是 cp1252 而不是预期的 utf-8.

Note that even after both suggested commands, my opened file's encoding is still cp1252 instead of the intended utf-8.

推荐答案

从 python3.5.1 开始,这个 hack 看起来像这样:

As of python3.5.1 this hack looks like this:

import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])

此后打开的所有文件将假定默认编码为 utf8.

All files opened thereafter will assume the default encoding to be utf8.

这篇关于在 Windows 中更改 Python 3 中的“语言环境首选编码"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆