我正在使用此代码从外部程序获取标准输出:
>>> 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.
我有一个tar文件,里面有多个文件.我需要编写一个python脚本,它将读取文件的内容并给出总字符数,包括字母总数,空格,换行符,所有内容,而不用解压缩tar文件.
如何打开一个开放的二进制流 - 一个Python 2 file,一个Python 3 io.BufferedReader,io.BytesIO一个io.TextIOWrapper?
我正在尝试编写将保持不变的代码:
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