>>> from subprocess import *>>> command_stdout = Popen(['ls','-l'],stdout=PIPE).communicate()[0]# u3 W4 `* @$ M& D. O5 n- |/ U0 @' }
communicate() 方法返回一个字节数组: + G' {2 Y# {+ @% N' @) A
>>> command_stdoutb'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' * c, k% }5 [3 x
但是,我想用输出作为普通 Python 字符串。这样我就可以这样打印了: # O2 v2 H! g W7 Q, ] v
>>> 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$ R7 j. }9 Q, O$ U! r1 P$ I
我想这就是binascii.b2a_qp()使用方法,但当我尝试它时,我得到了相同的字节数组: : O( i2 ^/ N" Y L
>>> 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' 7 T: s! i. B+ e7 S! O. @+ W1 _
如何将字节值转换为字符串?我的意思是使用电池而不是手动操作。我希望 Python 3 可以。 0 M+ J8 v- k: Y! T. @3 r+ [7 b/ D* P 2 ^* X/ D6 D d) V6 s解决方案: 1 g; _2 Y _, l# x& U( N
您需要解码 bytes 对象生成字符串:8 S! z. |. Z1 _1 Y
>>> 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' - X2 |* k- Q: Q x; o