回答

收藏

将字节转换为字符串

技术问答 技术问答 242 人阅读 | 0 人回复 | 2023-09-12

我使用此代码从外部程序获取标准输出:. e3 V. e$ Q) M1 ?& r( C2 Z
    >>> from subprocess import *>>> command_stdout = Popen(['ls','-l'],stdout=PIPE).communicate()[0]
    # `2 o+ O0 A, O; M+ b; r
communicate() 方法返回一个字节数组:$ ~- C0 v& c# I$ ]- X: Z1 H
    >>> 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'
    ! r: ^! O' l% l9 s9 G- a, M% n
但是,我想用输出作为普通 Python 字符串。这样我就可以这样打印了:! ]9 ]( t8 i3 u: y  B
    >>> 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 file23 I! J7 U) K( g. H4 d3 ^, W
我想这就是binascii.b2a_qp()使用方法,但当我尝试它时,我得到了相同的字节数组:
+ a! O( |4 Y" o% Y2 d
    >>> 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'0 T2 N9 [! m' e0 N
如何将字节值转换为字符串?我的意思是使用电池而不是手动操作。我希望 Python 3 可以。/ i- E2 I/ ?( }6 M8 Z1 }
                                                               
1 J, ~2 r5 j6 I. z8 C    解决方案:                                                                1 b3 Y& ?" _2 G
                                                                您需要解码 bytes 对象生成字符串:7 u. G( _- h( Y1 s0 I. U
    >>> 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'* G+ T, ]6 U0 Z
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则