为什么不是猴子补丁sys.getfilesystemcoding()?

2024-05-19 10:54:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中可以用sys.getfilesystemencoding()读取文件系统编码。在

但似乎没有正式的方法来设置文件系统编码。在

请参见:How to change file system encoding via python?

我发现了这个肮脏的黑客:

import sys
sys.getfilesystemencoding = lambda: 'UTF-8'

如果不能在启动解释器之前更改环境变量LANG,是否有更好的解决方案?在

背景,我为什么要这样:

这是有效的:

^{pr2}$

这不起作用:

user@host:~$ LANG=C python src/setfilesystemencoding.py 
LANG: C
sys.getdefaultencoding(): ascii
sys.getfilesystemencoding(): ANSI_X3.4-1968
Traceback (most recent call last):
  File "src/setfilesystemencoding.py", line 10, in <module>
    with open('/tmp/german-umlauts-üöä', 'wb') as fd:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 20-22: ordinal not in range(128)

下面是一个简单的脚本:

# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function

import os, sys

print('LANG: {}'.format(os.environ['LANG']))
print('sys.getdefaultencoding(): {}'.format(sys.getdefaultencoding()))
print('sys.getfilesystemencoding(): {}'.format(sys.getfilesystemencoding()))

with open('/tmp/german-umlauts-üöä', 'wb') as fd:
    fd.write('foo')

我希望上面的猴子修补可以解决这个问题。。。但是没有。对不起,这个问题再也没有意义了。我把它关上。在

我的解决方案:使用LANG=C.UTF-8


Tags: inpyimportsrcformat编码langsys

热门问题