python子进程编码

python子进程编码,python,encoding,subprocess,Python,Encoding,Subprocess,我正在尝试将powershell的输出存储在var中: import subprocess subprocess.check_call("powershell \"Get-ChildItem -LiteralPath 'HKLM:SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall' -ErrorAction 'Stop' -ErrorVariable '+ErrorUninstallKeyPath'\"", shell=

我正在尝试将powershell的输出存储在var中:

import subprocess
subprocess.check_call("powershell \"Get-ChildItem -LiteralPath 'HKLM:SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall' -ErrorAction 'Stop' -ErrorVariable '+ErrorUninstallKeyPath'\"", shell=True, stderr=subprocess.STDOUT)
这样,使用check_call打印ok,例如:

显示名称:Skype™

但这种方式只能打印到屏幕上,所以我必须使用

import subprocess
output = subprocess.check_output("powershell \"Get-ChildItem -LiteralPath 'HKLM:SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall' -ErrorAction 'Stop' -ErrorVariable '+ErrorUninstallKeyPath'\"", shell=True, stderr=subprocess.STDOUT)
但是,使用检查输出,我得到:

DisplayName:SkypeT


如何解决此问题?

输出类型为
字节
,因此您需要使用
.decode('utf-8')
(或使用您想要的任何编解码器)将其解码为字符串,或者使用
str()
,例如:

import subprocess
output_bytes = subprocess.check_output("powershell \"Get-ChildItem -LiteralPath 'HKLM:SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall' -ErrorAction 'Stop' -ErrorVariable '+ErrorUninstallKeyPath'\"", shell=True, stderr=subprocess.STDOUT)

output_string = str(output_bytes)
# alternatively
# output_string = output_bytes.decode('utf-8')

# there are lots of \r\n in the output I encounterd, so you can split
# to get a list
output_list = output_string.split(r'\r\n')

# once you have a list, you can loop thru and print (or whatever you want)
for e in output_list:
    print(e)

这里的关键是要解码到您想要使用的任何编解码器,以便在打印时生成正确的字符。

按照本文说明:

有可能绕过这个编码问题

import subprocess
output = subprocess.check_output("chcp 65001 | powershell \"Get-ChildItem -LiteralPath 'HKLM:SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall' -ErrorAction 'Stop' -ErrorVariable '+ErrorUninstallKeyPath'\"", shell=True, stderr=subprocess.STDOUT)

你好,谢谢你的回复,但结果是一样的。。。我在下面的帖子中解决了这个问题:我发布了一个带有正确代码的anwser