【问题标题】:Printing Unicode output from a subprocess to the terminal on Windows将 Unicode 输出从子进程打印到 Windows 上的终端
【发布时间】:2018-07-03 13:02:44
【问题描述】:

我正在尝试运行一个发出 Unicode 输出的命令,并将该输出打印到 shell。

我的代码类似于以下代码(CP850,因为这是我的 Windows 终端使用的代码页,由 chcp 返回):

command = 'echo Тестирование всегда необходимо!'
p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
out, err = p.communicate()
out = out.decode('CP850')
err = err.decode('CP850')
print(out)

我得到:?????????? ?????? ??????????!

我怎样才能使正确的文本通过?

【问题讨论】:

  • 我在 Howto 中找不到任何关于 Stdin/Stdout 或管道的信息。
  • CP850 不是 Unicode。如果你有一个支持 Unicode 的终端(和字体),CP850 就没有任何理由参与任何地方。

标签: python shell communication


【解决方案1】:

您为什么要像在 CP850 中一样解码此内容?没有理由这样做。

$ python
Python 2.7.10 (default, Oct  6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen, PIPE
>>> command = "echo 'Тестирование всегда необходимо!'"
>>> p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
>>> out, err = p.communicate()
>>> print out
Тестирование всегда необходимо!

同样,在 Python 3 上:

$ python3.6
Python 3.6.5 (default, Mar 29 2018, 15:37:32)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import Popen, PIPE
>>> command = "echo 'Тестирование всегда необходимо!'"
>>> p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
>>> out, err = p.communicate()
>>> print(out)
Тестирование всегда необходимо!

【讨论】:

  • 解码你是对的,但它在 3.6 上不起作用
  • 问题中需要指定Python版本。并查看使用 Python 3.6 脚本进行的编辑。如果您得到相反的结果,您需要分享其他人可以遵循的说明以查看它。
  • 我完全同意,版本很重要...这似乎是 Windows 7 的问题。我也无法在 Python Shell 中输入这些俄语字符。当我切换键盘布局时。我看到的都是问号。 >>> print('При-вет!') ???-???!
  • chcp 65001 有帮助吗?
猜你喜欢
  • 2020-02-24
  • 2014-06-18
  • 1970-01-01
  • 2014-01-01
  • 2011-06-26
  • 2020-01-06
  • 1970-01-01
  • 2020-09-18
相关资源
最近更新 更多