shell 将子进程的Unicode输出打印到Windows终端

nimxete2  于 2023-03-30  发布在  Shell
关注(0)|答案(2)|浏览(109)

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

我得到:?????????? ?????? ??????????!
我怎样才能使正确的文本通过?

bfhwhh0e

bfhwhh0e1#

为什么你要把这个内容解码成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)
Тестирование всегда необходимо!
m0rkklqb

m0rkklqb2#

我知道这个问题已经有将近5年的历史了,但是也许这对其他使用子进程的人有用,他们被迫使用管道来捕获python中的windows命令行输出。我刚刚花了几个小时在谷歌上搜索如何改变子进程的行为,并且未能改变Windows中文本管道的编码(我试过cmd /U和chcp 65001,将COMSPEC设置为cmd /U /C &&,并且locale无效).我对cmd的了解不够,无法使furoscame的代码与echo一起工作,但是我可以使用python -c“print('...')”作为替代(这正是我测试CLI所需要的)。
我发现关键是在衍生的shell中使用Python,在它的utf8模式下。然后它直接捕获输出为原始字节而不是文本,并手动解码。

import subprocess

command = '''python -X utf8 -c "print('Тестирование всегда необходимо!')"'''

result = subprocess.run(command, shell=True, capture_output = True) 
out = result.stdout.decode('utf8')
err = result.stderr.decode('utf8')

print(f'\n{command=}')
print(f'{out=}')
if err:
    print(f'{err=}')

在Windows 10中使用python.org的3.11安装程序

>python .\tests\so_eg.py 

command='python -X utf8 -c "print(\'Тестирование всегда необходимо!\')"'
out='Тестирование всегда необходимо!\r\n'

相关问题