我将外部程序的标准输出捕获到 bytes
对象中:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>>
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
我想把它转换成一个普通的 Python 字符串,这样我就可以像这样打印它:
>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
我尝试了 binascii.b2a_qp()
方法,但又得到了相同的 bytes
对象:
>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
如何使用 Python 3 将 bytes
对象转换为 str
?
原文由 Tomas Sedovic 发布,翻译遵循 CC BY-SA 4.0 许可协议
解码
bytes
对象 以生成字符串:上面的例子 假设
bytes
对象是 UTF-8,因为它是一种常见的编码。但是,您应该使用数据实际所在的编码!