如何打开一个开放的二进制流 - 一个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
我在同一个项目中使用windows和linux机器.Windows上stdin的默认编码是cp1252,linux上的默认编码是utf-8.
我想把一切都变成uft-8.可能吗?我该怎么做?