Skip to content

Latest commit

 

History

History
52 lines (37 loc) · 1.3 KB

65.md

File metadata and controls

52 lines (37 loc) · 1.3 KB
rank vote view answer url
65 1349 1258301 16 url

bytes 换成 string

我通过这个代码来获取外部程序的输出:

>>> 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 string. 像这样:

>>> 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'

谁知道怎么讲字节转换成 string ?


你需要 decode 字节对象来产生 string:

>>> b"abcde"
b'abcde'

# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8") 
'abcde'