回答

收藏

将字节转换为字符串

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

我使用此代码从外部程序获取标准输出:
+ H* R( H4 `& L- l
    >>> 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
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则