我正在使用以下代碼從外部程式獲取標準輸出:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
communication()方法回傳一個位元組陣列:
>>> 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物件以產生一個字串:
>>> 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'
本文首發于python黑洞網,博客園同步跟新
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/283102.html
標籤:其他
上一篇:Java基礎回顧-緩沖流
下一篇:如何在Java中創建記憶體泄漏?
