回答

收藏

将字节转换为字符串

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

我使用此代码从外部程序获取标准输出:
" U( ~" l+ w* c$ u3 I+ b: o& f8 V
    >>> from subprocess import *>>> command_stdout = Popen(['ls','-l'],stdout=PIPE).communicate()[0]) D. t8 J6 M& L+ u- o
communicate() 方法返回一个字节数组:9 R# ^! n/ y$ ^% Z3 o) N- O# [
    >>> 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'
    - N0 q, d8 [6 Z
但是,我想用输出作为普通 Python 字符串。这样我就可以这样打印了:
  u! q, Q% I* X
    >>> 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 `! }
我想这就是binascii.b2a_qp()使用方法,但当我尝试它时,我得到了相同的字节数组:
0 t- Z7 ]# j2 r$ W) M/ t. _9 X
    >>> 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'
    ( Y* A( z, p' ~! J8 ^
如何将字节值转换为字符串?我的意思是使用电池而不是手动操作。我希望 Python 3 可以。
3 m( N) d# ?; s: b2 t5 o# o8 I                                                               
( X. v: [: f( w* J$ D8 A    解决方案:                                                                " k3 w0 f5 g8 |9 \) N- d% r
                                                                您需要解码 bytes 对象生成字符串:
/ e. A# o; m8 b+ h- }+ E
    >>> 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'0 W. V) ]  k+ s5 ]: l
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则