在Windows中的Python 3中更改“区域设置首选编码" [英] Changing the “locale preferred encoding” in Python 3 in Windows

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

问题描述

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

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开始,此黑客看起来像这样:

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天全站免登陆