如何用Python [System.Console] :: OutputEncoding/InputEncoding`?

Art*_*yom 15 .net python shell powershell

在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
Run Code Online (Sandbox Code Playgroud)

打印:

Active code page: 65001
cp65001
cp1251
?»?????
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 8

您正在将数据传输到Python中; 在那时,Python stdin不再附加到TTY(您的控制台),也不会猜测编码可能是什么.而是使用默认系统区域设置; 在你的系统上是cp1251(基于Windows Latin-1的代码页).

设置PYTHONIOENCODING环境变量以覆盖:

PYTHONIOENCODING
如果在运行解释器之前设置了它,它将在语法中覆盖用于stdin/stdout/stderr的编码encodingname:errorhandler.无论是encodingname:errorhandler部分是可选的,并且具有的含义与相同str.encode().

PowerShell似乎不像UNIX shell那样支持每命令行环境变量; 最简单的方法是先设置变量:

Set-Item Env:PYTHONIOENCODING "UTF-8"
Run Code Online (Sandbox Code Playgroud)

甚至

Set-Item Env:PYTHONIOENCODING "cp65001"
Run Code Online (Sandbox Code Playgroud)

因为Windows UTF-8代码页显然不是真正的 UTF-8,具体取决于Windows版本,不管是否使用管道重定向.