我有一个用Python编写的 native 程序,希望它能在stdin上输入。举一个简单的例子
#!python3
import sys
with open('foo.txt', encoding='utf8') as f:
f.write(sys.stdin.read())
我希望能够将(PowerShell)字符串作为标准输入传递给该程序。 Python希望其标准输入采用
$env:PYTHONIOENCODING
中指定的编码,我通常将其设置为UTF8
(这样我就不会遇到任何编码错误)。但是无论我做什么,角色都会被破坏。我在网上搜索过,发现了一些建议来更改
[Console]::InputEncoding
/[Console]::OutputEncoding
或使用chcp
,但似乎没有任何效果。这是我的基本测试:
PS >[Console]::OutputEncoding.EncodingName
Unicode (UTF-8)
PS >[Console]::InputEncoding.EncodingName
Unicode (UTF-8)
PS >$env:PYTHONIOENCODING
utf-8
PS >python -c "print('\N{Euro sign}')" | python -c "import sys; print(sys.stdin.read())"
´╗┐?
PS >chcp 1252
Active code page: 1252
PS >python -c "print('\N{Euro sign}')" | python -c "import sys; print(sys.stdin.read())"
?
PS >chcp 65001
Active code page: 65001
PS >python -c "print('\N{Euro sign}')" | python -c "import sys; print(sys.stdin.read())"
?
我该如何解决这个问题?
我什至无法解释这里发生了什么。基本上,我希望测试(
python -c "print('\N{Euro sign}')" | python -c "import sys; print(sys.stdin.read())"
)打印出一个欧元符号。并且要理解为什么,我必须做所有必要的工作才能使它工作:-)(因为这样我就可以将这些知识转化为我的真实情况,即能够编写不中断的Python程序的工作流水线当他们遇到Unicode字符时)。 最佳答案
感谢mike z,以下工作有效:
$OutputEncoding = [Console]::OutputEncoding = (new-object System.Text.UTF8Encoding $false)
$env:PYTHONIOENCODING = "utf-8"
python -c "print('\N{Euro sign}')" | python -c "import sys; print(sys.stdin.read())"
需要
new-object
来获得没有UTF-8的BOM编码。 $OutputEncoding
变量和[Console]::OutputEncoding
似乎都需要设置。我仍然不完全了解两个编码值之间的区别,以及为什么要对它们进行不同的设置(这似乎是默认设置)。
关于python - 如何将Unicode传递到PowerShell中的 native 应用程序中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25642746/