【问题标题】:python subprocess encodingpython子进程编码
【发布时间】:2018-08-15 11:23:33
【问题描述】:

我正在尝试将 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,就可以打印了,例如:

显示名称: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)

然后,使用 check_output,我得到:

显示名称:SkypeT

我该如何解决这个问题?

【问题讨论】:

    标签: python encoding subprocess


    【解决方案1】:

    按照此帖子说明操作:How to make Unicode charset in cmd.exe by default?

    有可能绕过这个编码问题

    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)
    

    【讨论】:

      【解决方案2】:

      输出是bytes 类型的,因此您需要将其解码为带有.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)
      

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

      【讨论】:

      • 你好,谢谢你的回复,但结果是一样的......我设法在这篇文章之后解决了它:link我正在发布一个带有正确代码的anwser