Python脚本打印unicode,在shell中使用``导致错误

Mit*_*del 1 python unicode bash python-2.7

我有一个名为a.py的Python脚本:

#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
print u'????'
Run Code Online (Sandbox Code Playgroud)

在bash和tcsh中:

$ a.py
Ô£øÔ£øÔ£øÔ£ø
$ echo `a.py`
Traceback (most recent call last):
  File "a.py", line 3, in <module>
    print u'Ô£øÔ£øÔ£øÔ£ø'
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

错误来自Python,而不是shell.如何在反引号下运行脚本会影响脚本本身?请注意,如果我在脚本开头将解释器切换到Python 3,这不是问题.

R. *_* Q. 7

当Python没有检测到它正在打印到终端时,就像子shell中的情况一样,sys.stdout.encoding设置为None.打印unicode时,使用ascii编解码器(至少在Python2中).如果unicode包含0-127之外的代码点,则会导致UnicodeError.

解决此问题的方法是将PYTHONIOENCODING环境变量设置为适当的编码.例如:

export PYTHONIOENCODING=utf-8; echo `a.py`
Run Code Online (Sandbox Code Playgroud)

这个的功劳去unutbu!