首页 > 解决方案 > 将子进程的 Unicode 输出打印到 Windows 上的终端

问题描述

我正在尝试运行一个发出 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)

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

如何使正确的文本通过?

标签: pythonshellcommunication

解决方案


您为什么要像在 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)
Тестирование всегда необходимо!

推荐阅读