Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

python - 将字节转换为字符串(Convert bytes to a string)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to decode the bytes object to produce a string:

(您需要解码bytes对象以产生一个字符串:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...