將位元組轉換為字串 - Convert bytes to a string

語言: CN / TW / HK

問題:

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:通訊()方法返回一個位元組陣列:

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

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

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 沒問題。


解決方案:

參考一: https://stackoom.com/question/2XhH
參考二: Convert bytes to a string
「其他文章」