【问题标题】:Python subprocess.Popen() doesn't show correct stdout subprocess.call()Python subprocess.Popen() 没有显示正确的标准输出 subprocess.call()
【发布时间】:2017-04-26 11:57:40
【问题描述】:

当我在 Windows 7 中执行以下脚本时,它会为这两种情况显示不同的标准输出格式。第一个标准输出显示内联字符串,第二个标准输出显示与在 Windows cmd.exe 中执行命令相同。我的代码有什么问题?


import subprocess

process = subprocess.Popen(['dir'], stdout=subprocess.PIPE, shell=True)
stdout = process.communicate()[0]
print('STDOUT:{}'.format(stdout)) #first stdout

subprocess.call('dir', shell=True) #second stdout

第一个标准输出

C:\ProgramData\Anaconda3\python.exe C:/Users/user/PycharmProject/spython_to_cmd_communication.py
STDOUT:b' C \xb5\xe5\xb6\xf3\xc0\xcc\xba\xea\xc0\xc7 \xba\xbc\xb7\xfd: Windows7\r\n \xba\xbc\xb7\xfd \xc0\xcf\xb7\xc3 \xb9\xf8\xc8\xa3: 8623-6624\r\n\r\n C:\\Users\\user\\PycharmProjects\xb5\xf0\xb7\xba\xc5\xcd\xb8\xae\r\n\r\n2017-04-26  \xbf\xc0\xc8\xc4 08:44    <DIR>          .\r\n2017-04-26  \xbf\xc0\xc8\xc4 08:44    <DIR>          ..\r\n2017-04-26  \xbf\xc0\xc8\xc4 08:44    <DIR>          .idea\r\n2017-04-20  \xbf\xc0\xc8\xc4 08:03             2,652  \xbf\xc0\xc8\xc4 08:29             4,664 listing_stock_code_business.py\r\n2017-04-26  \xbf\xc0\xc8\xc4 08:44               241 python_to_cmd_communication.py\r\n2017-04-20  \xbf\xc0\xc8\xc4 08:24             1,780   \xbf\xc0\xc8\xc4 08:24    <DIR>          __pycache__\r\n               4\xb0\xb3 \xc6\xc4\xc0\xcf               9,337 \xb9\xd9\xc0\xcc\xc6\xae\r\n               4\xb0\xb3 \xb5\xf0\xb7\xba\xc5\xcd\xb8\xae  38,024,884,224 \xb9\xd9\xc0\xcc\xc6\xae \xb3\xb2\xc0\xbd\r\n'
 C ����̺��� ����: Windows7
 ���� �Ϸ� ��ȣ: 8

第二个标准输出

C:\Users\user\PycharmProjects\python_to_cmd_communication���͸�

2017-04-26  ���� 08:44    <DIR>          .
2017-04-26  ���� 08:44    <DIR>          ..
2017-04-26  ���� 08:44    <DIR>          .idea
2017-04-26  ���� 08:44               241 python_to_cmd_communication.py
2017-04-20  ���� 08:24    <DIR>          __pycache__
               4�� ����               9,337 ����Ʈ
               4�� ���͸�  38,024,884,224 ����Ʈ ����

Process finished with exit code 0

【问题讨论】:

  • stdout 是一个类似文件的对象,而不是字符串。您需要从中读取字符串,而不是将对象转换为单个字符串。
  • subprocess.call 不会将stdout 重定向到管道,因此 cmd.exe 将 16 位宽的字符直接写入控制台。第一种情况将stdout 重定向到管道,因此 cmd.exe 使用当前控制台代码页对写入管道的输出进行编码。您似乎将控制台设置为代码页 936(简体中文),因此您需要将输出解码为 stdout.decode('cp936')
  • 我建议将控制台配置为使用支持您首选语言环境的字体,这样输出中就不会填充诸如“����”之类的替换字符。
  • 谢谢所有的cmets。通过添加 '.decode('cp949') print('STDOUT:}'.format(stdout.decode('cp949')) #first stdout 解决了问题

标签: python windows subprocess


【解决方案1】:

这类似于调用相同内容的exe文件。您有时可以安装 python pip install x 或 conda pip install x 或 vs python pip install x。

【讨论】:

    猜你喜欢
    • 2011-10-19
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2021-05-19
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多