在Windows上将Unicode输出从子进程打印到终端

时间:2018-07-03 13:02:45

标签: python shell communication

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

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

如何使正确的文字通过?

1 个答案:

答案 0 :(得分:2)

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