Python 3的open()在Windows下的默认编码。 sys.getdefaultencoding()设置不受尊重 [英] Default encoding of Python 3's open() under Windows. sys.getdefaultencoding() setting not respected

查看:1230
本文介绍了Python 3的open()在Windows下的默认编码。 sys.getdefaultencoding()设置不受尊重的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这个问题上拉了我的头发了几个小时。



我有一个消息文件,我想使用django的makemessages命令生成,它的工作原理在一个Linux环境中,实际上以一种理智的方式处理区域设置。但是,当我在Windows下尝试相同的事情时,每次python尝试打开一个文件时,它假定它是编码在 cp932 (SHIFT-JIS)中,它会导致所有种类破坏性的。



手动将 encoding ='utf-8'添加到每个 / code>呼叫工作,但这几乎不是解决问题的好方法。有没有办法强制打开使用特定的默认编码?




  • sys.getdefaultencoding()返回'utf-8',因为某些神秘的原因,这个设置是不被尊重的

  • PYTHONIOENCODING和PYTHONENCODING都被设置到'utf-8'

  • 我的代码页设置为 cp65001



这是我的python版本字符串:



Python 3.3.2(v3.3.2:d047928ae3f6,May 16 2013,00:06:53)[MSC v.1600 64位(AMD64)]在win32上



编辑:我注意到 locale.getpreferredencoding()返回 cp932 ,所以我想找到一个Windows区域设置, utf -8 作为其默认值会做的。这样的事情是否存在?

解决方案

尝试这个

  import locale 
locale.setlocale(locale.LC_ALL,'en_US.utf-8')


I've been pulling my hair out over this issue for several hours now.

I have a message file I want to generate using django's makemessages command, which works just fine in a Linux environment which actually handles locale settings in a sane way. However, when I try the same thing under Windows, every time python tries to open a file, it assumes it is encoded in cp932 (SHIFT-JIS), which causes all sorts of havoc.

Manually adding encoding='utf-8' to every open call works, but that's hardly a good way of fixing the problem. Is there any way to force open to use a specific default encoding?

  • sys.getdefaultencoding() returns 'utf-8', for some arcane reason this setting is not respected
  • PYTHONIOENCODING and PYTHONENCODING are both set to 'utf-8'
  • My code page is set to cp65001

This is my python version string:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32

EDIT: I've noticed that locale.getpreferredencoding() returns cp932, so I guess finding a Windows locale with utf-8 as its default would do the trick. Does such a thing even exist?

解决方案

Try this

import locale
locale.setlocale(locale.LC_ALL, 'en_US.utf-8')

这篇关于Python 3的open()在Windows下的默认编码。 sys.getdefaultencoding()设置不受尊重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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