在 Powershell v5、Windows 8.1、Python 3 下。为什么会失败以及如何修复?
[system.console]::InputEncoding = [System.Text.Encoding]::UTF8;
[system.console]::OutputEncoding = [System.Text.Encoding]::UTF8;
chcp;
"import sys
print(sys.stdout.encoding)
print(sys.stdin.encoding)
sys.stdout.write(sys.stdin.readline())
" |
sc test.py -Encoding utf8;
[char]0x0422+[char]0x0415+[char]0x0421+[char]0x0422+"`n" | py -3 test.py
打印:
Active code page: 65001
cp65001
cp1251
п»ї????
最佳答案
您正在将数据通过管道传输到 Python;那时 Python 的 stdin
不再附加到 TTY(您的控制台)并且不会猜测编码可能是什么。相反,使用默认的系统语言环境;在您的系统上是 cp1251(基于 Windows Latin-1 的代码页)。
设置PYTHONIOENCODING
environment variable覆盖:
PYTHONIOENCODING
If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntaxencodingname:errorhandler
. Both theencodingname
and the:errorhandler
parts are optional and have the same meaning as instr.encode()
.
PowerShell 似乎不像 UNIX shell 那样支持每个命令行环境变量;最简单的方法是先设置变量:
Set-Item Env:PYTHONIOENCODING "UTF-8"
甚至
Set-Item Env:PYTHONIOENCODING "cp65001"
因为 Windows UTF-8 代码页显然完全不是真正的 UTF-8,这取决于 Windows 版本以及是否使用管道重定向。
关于python - `[System.Console]::OutputEncoding/InputEncoding`怎么用Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39183614/