如何在PowerShell中将Unicode管道传输到本机应用程序中

时间:2014-09-03 11:06:30

标签: python powershell unicode encoding pipeline

我有一个用Python编写的本机程序,期望它在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字符时不会中断。)

1 个答案:

答案 0 :(得分:3)

感谢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())"

获得UTF-8编码时需要new-object而不需要BOM。 <{1}}变量和$OutputEncoding似乎都需要设置。

我仍然不完全理解两个编码值之间的区别,以及为什么你会设置不同的(这似乎是默认值)。