在 Bash shell 中,为什么 Python 仅在输出重定向或通过管道传输时才抱怨打印非 ascii 字符?

Jia*_*ian 2 python bash

打印终端:

\n\n
> python -c \'print u"\\xae"\' # no complaints here!\n\xc2\xae\n
Run Code Online (Sandbox Code Playgroud)\n\n

打印到文件:

\n\n
> python -c \'print u"\\xae"\' > tmp.txt\nTraceback (most recent call last):\n  File "<string>", line 1, in <module>\nUnicodeEncodeError: \'ascii\' codec can\'t encode character u\'\\xae\' in position 0: ordinal not in range(128)\n
Run Code Online (Sandbox Code Playgroud)\n\n

当管道传输到cat例如,

\n

Ign*_*ams 5

因为它无法正确猜测编码并假设它是“ascii”。当输出不是 TTY 时编码为 UTF-8。