回答

收藏

将字节转换为字符串

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

我使用此代码从外部程序获取标准输出:
) j& L; O4 g8 x: H) V# @0 m
    >>> from subprocess import *>>> command_stdout = Popen(['ls','-l'],stdout=PIPE).communicate()[0]) Z/ v- q7 p$ |, m$ Q5 Q1 |5 Q1 z
communicate() 方法返回一个字节数组:, A' i0 X2 _$ A' j6 j9 L8 X
    >>> 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'* Y6 ~  ]- ~' |  G
但是,我想用输出作为普通 Python 字符串。这样我就可以这样打印了:4 n6 ^; s, y, `9 ^( [" A( r/ C
    >>> 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
    0 q* ^- a- n/ ^. B* t2 t9 W$ V+ q
我想这就是binascii.b2a_qp()使用方法,但当我尝试它时,我得到了相同的字节数组:
, @- t' r. D% S7 P
    >>> 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'
    ) Q* r7 `; x- s* a
如何将字节值转换为字符串?我的意思是使用电池而不是手动操作。我希望 Python 3 可以。
* p6 V4 @5 `( l( U  u2 y: G                                                                9 K/ }3 I" l2 Q' t" Y
    解决方案:                                                               
( P# d0 M8 g  c; L0 g7 i                                                                您需要解码 bytes 对象生成字符串:
: d1 o9 z& a+ M- E7 f- e/ V- D6 i
    >>> 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'
    + }! E  u/ L  L+ D/ P
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则