我将外部程序的标准输出捕获到一个 bytes
对象中:
>>> from subprocess import *
>>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>> 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(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中的
bytes
对象转换为str
?
查看在Python 3中将字符串转换为字节的最佳方法以了解另一种方式。
str(text_bytes)
不起作用?这对我来说似乎很奇怪。 - Charlie Parkerstr(text_bytes)
无法指定编码方式。根据text_bytes
中包含的内容,使用text_bytes.decode('cp1250')
可能会得到与text_bytes.decode('utf-8')
截然不同的字符串。 - Craig Andersonstr
函数不再自动将其它类型转换为字符串。由于某些原因,必须显式指定编码方式。只需要将编码方式设置为utf-8
并检查你的代码是否正常工作即可。例如:var = var.decode('utf-8')
。 - Charlie Parkerunicode_text = str(bytestring, character_encoding)
可以正常工作。虽然unicode_text = bytestring.decode(character_encoding)
更可取,以避免与仅为bytes_obj
生成文本表示的str(bytes_obj)
混淆,而不是将其解码为文本:str(b'\xb6', 'cp1252') == b'\xb6'.decode('cp1252') == '¶'
,并且str(b'\xb6') == "b'\\xb6'" == repr(b'\xb6') != '¶'
。 - jfstext=True
传递给subprocess.run()
或.Popen()
,然后您将获得一个字符串,无需转换字节。或者在任一函数中指定encoding="utf-8"
。 - David Gilbertsonstr(<bytes>)
时得到的字符串的用例,但也许只是为了与其他str
调用保持一致。我本以为它们可以默认为UTF-8编码,但也许是因为Windows有太多奇怪的编码方式,所以它不会默认为UTF-8;但我同意你的观点。 - NeilG