这取决于您的输出流编码。在这种特定情况下,由于您使用了print
,所使用的输出文件是sys.stdout
。
交互模式 / 未重定向 stdout
当您在交互模式下运行Python,或者当您未将stdout
重定向到文件时,Python会使用基于环境的编码,即区域设置环境变量,例如LC_CTYPE
。例如,如果您像这样运行程序:
$ LC_CTYPE='en_US' python test.py
...
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128)
如果使用 ANSI_X3.4-1968
作为 sys.stdout
的编码(参见 sys.stdout.encoding
),则可能会出现问题。但是,如果使用 UTF-8
(显然您已经这样做了):
$ LC_CTYPE='en_US.UTF-8' python test.py
1234567890
abcd
αβγδ
您将获得预期的输出。
stdout
重定向到文件
当您将 stdout
重定向到文件时,Python 不会尝试从环境区域设置中检测编码,但它会检查另一个环境变量 PYTHONIOENCODING
(请查看源代码,Python/pylifecycle.c
中的 initstdio()
)。例如,这将按预期工作:
$ PYTHONIOENCODING=utf-8 python test.py >/tmp/output
由于Python将使用UTF-8
编码的/tmp/output
文件。
手动覆盖stdout
编码
您还可以使用所需的编码手动重新打开sys.stdout
(请参阅this和this SO问题):
import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
现在,
print
将正确输出
str
和
unicode
对象,因为底层流编写器将在运行时将它们转换为
UTF-8
。
手动进行字符串编码以进行输出
当然,您也可以使用以下方式手动将每个
unicode
编码为
UTF-8
str
以进行输出:
print ('%5s' % s2).encode('utf8')
但这很繁琐且容易出错。
显式文件打开
为了完整起见:在Python 2中以特定编码(如UTF-8)打开文件进行写入时,应使用io.open
或codecs.open
,因为它们允许您指定编码(请参见this question),而内置的open
则不允许。
from codecs import open
myfile = open('filename', encoding='utf-8')
或者:
from io import open
myfile = open('filename', encoding='utf-8')