Python如何使用[[System.Console] :: OutputEncoding / InputEncoding`? [英] How `[System.Console]::OutputEncoding/InputEncoding` with Python?
问题描述
在Powershell v5,Windows 8.1,Python 3中。为什么这些失败以及如何解决?
Under Powershell v5, Windows 8.1, Python 3. Why these fails and how to fix?
[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的代码页)上。
You are piping data into Python; at that point Python's stdin
is no longer attached to a TTY (your console) and won't guess at what the encoding might be. Instead, the default system locale is used; on your system that's cp1251 (the Windows Latin-1-based codepage).
设置 PYTHONIOENCODING
环境变量来覆盖:
Set the PYTHONIOENCODING
environment variable to override:
PYTHONIOENCODING
如果在运行解释器之前设置了该值,它将覆盖stdin / stdout / stderr中使用的编码。语法encodingname:errorhandler
。编码名
和:errorhandler
部分都是可选的,其含义与str .encode()
。
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的方式;最简单的方法是先设置变量:
PowerShell doesn't appear to support per-command-line environment variables the way UNIX shells do; the easiest is to just set the variable first:
Set-Item Env:PYTHONIOENCODING "UTF-8"
甚至
Set-Item Env:PYTHONIOENCODING "cp65001"
因为Windows UTF-8代码页显然不是确实 UTF-8,取决于Windows版本以及是否使用管道重定向。
as the Windows UTF-8 codepage is apparently not quite UTF-8 really, depending on the Windows version and on wether or not pipe redirection is used.
这篇关于Python如何使用[[System.Console] :: OutputEncoding / InputEncoding`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!