我正在使用此代码从外部程序获取标准输出:
>>> 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()方法的作用,但当我尝试它时,我又得到了相同的字节数组:
>>> 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对象以生成字符串:
我觉得这样很简单:
您需要解码字节字符串并将其转换为字符(Unicode)字符串。
关于Python 2
或者
在Python 3上
或者
相关问题 更多 >
编程相关推荐