相关疑难解决方法(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脚本中读取tar文件内容而不解压缩它

我有一个tar文件,里面有多个文件.我需要编写一个python脚本,它将读取文件的内容并给出总字符数,包括字母总数,空格,换行符,所有内容,而不用解压缩tar文件.

python tar

72
推荐指数
3
解决办法
5万
查看次数

用io.TextIOWrapper包装一个开放的流

如何打开一个开放的二进制流 - 一个Python 2 file,一个Python 3 io.BufferedReader,io.BytesIO一个io.TextIOWrapper

我正在尝试编写将保持不变的代码:

  • 在Python 2上运行.
  • 在Python 3上运行.
  • 使用从标准库生成的二进制流(即我无法控制它们的类型)
  • 使用二进制流进行测试双精度(即没有文件句柄,无法重新打开).
  • 生成io.TextIOWrapper包装指定流的包.

io.TextIOWrapper是必需的,因为它的API是标准库的其他部分所期望的.存在其他类似文件的类型,但不提供正确的API.

将二进制流包装为subprocess.Popen.stdout属性:

import subprocess
import io

gnupg_subprocess = subprocess.Popen(
        ["gpg", "--version"], stdout=subprocess.PIPE)
gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout, encoding="utf-8")
Run Code Online (Sandbox Code Playgroud)

在单元测试中,流被io.BytesIO实例替换以控制其内容,而不触及任何子进程或文件系统.

gnupg_subprocess.stdout = io.BytesIO("Lorem ipsum".encode("utf-8"))
Run Code Online (Sandbox Code Playgroud)

这适用于Python 3标准库创建的流.但是,相同的代码在Python 2生成的流上失败:

[Python 2]
>>> type(gnupg_subprocess.stdout)
<type 'file'>
>>> gnupg_stdout = io.TextIOWrapper(gnupg_subprocess.stdout, encoding="utf-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'file' object has …
Run Code Online (Sandbox Code Playgroud)

python unit-testing character-encoding python-2.x python-3.x

32
推荐指数
3
解决办法
2万
查看次数