我正在使用此代码从外部程序获取标准输出:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
communic()方法返回一个字节数组:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
但是,我想将输出作为普通的Python字符串.所以我可以这样打印:
>>> 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
Run Code Online (Sandbox Code Playgroud)
我认为这是binascii.b2a_qp()方法的用途,但是当我尝试它时,我又得到了相同的字节数组:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
有人知道如何将字节值转换回字符串吗?我的意思是,使用"电池"而不是手动操作.而且我希望它能用于Python 3.
我是 Python 的新手(C 是我的主要语言),所以这可能是一个超级基本/幼稚的问题。
我有两个使用以下 Python 代码生成的整数列表:
mainList = range(100)
random.shuffle(mainList)
list1 = mainList[:len(mainList)/2]
list2 = mainList[len(mainList)/2:]
Run Code Online (Sandbox Code Playgroud)
基本上,我试图通过 TCP 连接发送这些列表(list1
和list2
)中的每一个,并且我想确保我只为每个列表发送 50 字节的有效负载(每个列表包含 50 个整数)。
什么是最好的方法来做到这一点?该bytearray()
功能是否适用于这里?