显示子进程check_output的可读输出

时间:2015-10-20 01:54:04

标签: python python-3.x subprocess output tokenize

如何使人类可读的subprocess.check_output(args, "command")输出?我已经研究过这个主题,并且已经找到了如何“标记化”而不是 erm .. “去标记化”输出。 我下面的示例代码是相对于我所追求的,但为了更好地解释,当我打印出string = subprocess.check_output(...)输出的字符串时,它几乎无法理解。

代码:

from subprocess import *
readOutput = check_output(
    "dir",
    shell = True)
print(readOutput)`

输出

b' Volume in drive C has no label.\r\n Volume Serial Number is 2AAE-9786\r\n\r\n Directory of C:\\Users\\spike\\Documents\\GitHub\\GitterGUI\\example\r\n\r\n10/19/2015  06:29 PM    <DIR>          .\r\n10/19/2015  06:29 PM    <DIR>          ..\r\n10/19/2015  06:29 PM                60 batfile.bat\r\n10/19/2015  06:26 PM                 0 New Bitmap Image.bmp\r\n10/19/2015  06:26 PM                22 New Compressed (zipped) Folder.zip\r\n10/19/2015  06:26 PM    <DIR>          New folder\r\n10/19/2015  06:26 PM    <DIR>          New folder (2)\r\n10/19/2015  06:26 PM                 0 New Text Document (2).txt\r\n10/19/2015  06:26 PM                 0 New Text Document (3).txt\r\n10/19/2015  06:26 PM                 0 New Text Document.txt\r\n10/19/2015  06:27 PM                96 script.py\r\n               7 File(s)            178 bytes\r\n               4 Dir(s)  819,483,295,744 bytes free\r\n'

应该是:

 Volume in drive C has no label.
 Volume Serial Number is 2AAE-9786

 Directory of C:\Users\spike\Documents\GitHub\GitterGUI\example

10/19/2015  06:29 PM    <DIR>          .
10/19/2015  06:29 PM    <DIR>          ..
10/19/2015  06:29 PM                60 batfile.bat
10/19/2015  06:26 PM                 0 New Bitmap Image.bmp
10/19/2015  06:26 PM                22 New Compressed (zipped) Folder.zip
10/19/2015  06:26 PM    <DIR>          New folder
10/19/2015  06:26 PM    <DIR>          New folder (2)
10/19/2015  06:26 PM                 0 New Text Document (2).txt
10/19/2015  06:26 PM                 0 New Text Document (3).txt
10/19/2015  06:26 PM                 0 New Text Document.txt
10/19/2015  06:27 PM                96 script.py
               7 File(s)            178 bytes
               4 Dir(s)  819,481,882,624 bytes free

如您所见,我的脚本需要认真工作。提前谢谢。

1 个答案:

答案 0 :(得分:2)

使用print((readOutput).decode('utf-8')) 而不是print(readOutput)

问题是字符串readOutput的输出不是Unicode格式。

修改

我喜欢这个回复:

  

“或者,将universal_newlines=True传递给check_output以使其自动解码。”

- ShadowRanger