我将外部程序的标准输出捕获到一个字节对象中:
>>> 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
如何使用Python 3将字节对象转换为str?
对于“运行shell命令并将其输出作为文本而不是字节”的特定情况,在Python 3.7上,应该使用subprocess.run并传入text=True(以及capture_output=True来捕获输出)
command_result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
command_result.stdout # is a `str` containing your program's stdout
文本过去被称为universal_newlines,在Python 3.7中被更改(嗯,别名)。如果希望支持3.7之前的Python版本,请传入universal_newlines=True而不是text=True
我们可以使用bytes.decode(encoding='utf-8',errors='strict')对bytes对象进行解码以生成字符串。有关文档,请参阅bytes.decode。
Python 3示例:
byte_value = b"abcde"
print("Initial value = {}".format(byte_value))
print("Initial value type = {}".format(type(byte_value)))
string_value = byte_value.decode("utf-8")
# utf-8 is used here because it is a very common encoding, but you need to use the encoding your data is actually in.
print("------------")
print("Converted value = {}".format(string_value))
print("Converted value type = {}".format(type(string_value)))
输出:
Initial value = b'abcde'
Initial value type = <class 'bytes'>
------------
Converted value = abcde
Converted value type = <class 'str'>
注意:在Python 3中,默认情况下编码类型为UTF-8。因此,<byte_string>.decode(“utf-8”)也可以写成<byte-string>.decode()
对于“运行shell命令并将其输出作为文本而不是字节”的特定情况,在Python 3.7上,应该使用subprocess.run并传入text=True(以及capture_output=True来捕获输出)
command_result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
command_result.stdout # is a `str` containing your program's stdout
文本过去被称为universal_newlines,在Python 3.7中被更改(嗯,别名)。如果希望支持3.7之前的Python版本,请传入universal_newlines=True而不是text=True