【发布时间】:2022-01-18 18:35:31
【问题描述】:
我正在使用此代码从外部程序获取标准输出:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
communicate() 方法返回一个字节数组:
>>> 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() 方法的用途,但是当我尝试它时,我又得到了相同的字节数组:
>>> 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 也可以。
【问题讨论】:
-
为什么
str(text_bytes)不起作用?这对我来说似乎很奇怪。 -
@CharlieParker 因为
str(text_bytes)无法指定编码。根据 text_bytes 中的内容,text_bytes.decode('cp1250)` 可能会导致与text_bytes.decode('utf-8')完全不同的字符串。 -
所以
str函数不再转换为真正的字符串。由于某种原因,我不得不明确地说出一种编码,我懒得通读原因。只需将其转换为utf-8并查看您的代码是否有效。例如var = var.decode('utf-8') -
@CraigAnderson:
unicode_text = str(bytestring, character_encoding)在 Python 3 上按预期工作。尽管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') != '¶'
标签: python string python-3.x