python - 将子进程的 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)
我得到:?????????? ?????? ??????????!
如何使正确的文本通过?
解决方案
您为什么要像在 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)
Тестирование всегда необходимо!
推荐阅读
- mysql - XAMPP:MySQL 意外关闭,已尝试重新安装一切仍然无法正常工作
- javascript - 消除重复无法按预期工作
- javascript - 如何在 javascript 中生成的动态 html 元素上应用 .css 规则
- c# - 有没有简单的方法可以使用未知字符作为“ sim.Keyboard.KeyPress”的输入?
- java - java.lang.IllegalStateException:应在主线程上调用,但为 RxCachedThreadScheduler-1
- c++ - 为什么 j 需要小于或等于 sqrt(i)?
- aptitude - 能力(基于时间和工作的问题(Wipro)))
- python - 如何将空格分隔的字符串输入作为 OrderedDict 的键?
- python-3.x - python:从外部文件动态加载函数
- django - 限制对 Django 中对象的访问