python - `[System.Console]::OutputEncoding/InputEncoding`怎么用Python?

标签 python .net 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

打印:

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 syntax encodingname:errorhandler. Both the encodingname and the :errorhandler parts are optional and have the same meaning as in str.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/

相关文章:

linux - 通过 nohup 终止 matlab 运行并访问工作区变量

python - 使用Tensorflow对图像进行分类时如何获取识别对象的像素矩阵?

python - pip uninstall broken with -py2.7 in egg path

python - pywinauto:如何使用wrapper_object()给出的内存位置字符串?

c# - 更改数据库位置会删除所有者模式

c# - ICollection to String 在 C# 中以良好的格式

linux - 如何使 rsync 从 STDIN 读取 SRC?

python - Django QuerySet 过滤器 + order_by + 限制

c# - 服务器端的计时器?

linux - 如何使用 grep match 作为变量(而不是整行)