I'm using this code to get standard output from an external program:
(我正在使用以下代码从外部程序获取标准输出:)
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
The communicate() method returns an array of bytes:
(communication()方法返回一个字节数组:)
>>> command_stdout
b'total 0
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
'
However, I'd like to work with the output as a normal Python string.
(但是,我想将输出作为普通的Python字符串使用。)
So that I could print it like this: (这样我就可以像这样打印它:)
>>> 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
I thought that's what the binascii.b2a_qp() method is for, but when I tried it, I got the same byte array again:
(我以为那是binascii.b2a_qp()方法的用途,但是当我尝试它时,我又得到了相同的字节数组:)
>>> binascii.b2a_qp(command_stdout)
b'total 0
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
'
How do I convert the bytes value back to string?
(如何将字节值转换回字符串?)
I mean, using the "batteries" instead of doing it manually. (我的意思是,使用“电池”而不是手动进行操作。)
And I'd like it to be OK with Python 3. (我希望它与Python 3兼容。)
ask by Tomas Sedovic translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…