相关疑难解决方法(0)

将字节转换为字符串?

我正在使用此代码从外部程序获取标准输出:

>>> 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 string python-3.x

1968
推荐指数
18
解决办法
203万
查看次数

在Python中序列化二进制数据

我有一些二进制数据,在 Python 中以字节字符串数组的形式存在。

是否有一种可移植的方法来序列化其他语言可以读取的数据?

JSON 失败是因为我刚刚发现它没有真正的方法来存储二进制数据;它的字符串应该是 Unicode。

我不想使用,pickle因为我不想承担安全风险,这限制了它在其他 Python 程序中的使用。

有什么建议吗?我真的很想使用一个内置库(或者至少是标准 Anaconda 发行版的一部分)。

python binary serialization python-2.7

5
推荐指数
1
解决办法
8086
查看次数

标签 统计

python ×2

binary ×1

python-2.7 ×1

python-3.x ×1

serialization ×1

string ×1