如何使人类可读的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
如您所见,我的脚本需要认真工作。提前谢谢。
答案 0 :(得分:2)
使用print((readOutput).decode('utf-8'))
而不是print(readOutput)
问题是字符串readOutput
的输出不是Unicode格式。
修改强>
我喜欢这个回复:
“或者,将
universal_newlines=True
传递给check_output
以使其自动解码。”