ils*_*tam 2 python byte subprocess decode python-3.x
我正在使用子进程运行一个进程:
\n\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE)\nRun Code Online (Sandbox Code Playgroud)\n\n我想要做的是循环中一个一个地读取输出字符:
\n\nwhile something:\n char = p.stdout.read(1)\nRun Code Online (Sandbox Code Playgroud)\n\n在 python3 中subprocess.Popen().stdout.read()返回bytes()不str()。我想将它用作 str 所以我必须这样做:
char = char.decode("utf-8")\nRun Code Online (Sandbox Code Playgroud)\n\n它可以很好地处理 ascii 字符。
\n\n但对于非 ascii 字符(例如希腊字母),我得到一个 UnicodeDecodeError。这就是为什么希腊字符由多个字节组成的原因。问题是这样的:
\n\n>>> b\'\\xce\\xb5\'.decode(\'utf-8\')\n\'\xce\xb5\'\n>>> b\'\\xce\'.decode(\'utf-8\') # b\'\\xce\' is what subprocess...read(1) returns - one byte\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nUnicodeDecodeError: \'utf-8\' codec can\'t decode byte 0xce in position 0: unexpected end of data\n>>> \nRun Code Online (Sandbox Code Playgroud)\n\n我该如何处理这个问题?\n的输出subprocess.Popen().stdout.read()(作为字符串)的输出可能类似于“lorem ipsum \xce\xb5\xcf\x86\xce\xb4\xcf\x86\xce\xb4\xcf\x83loremipsum”。
我想一次读取一个字符,但该字符可以由多个字节组成。
\n将文件对象包装起来io.TextIOWrapper()以动态解码管道:
import io
reader = io.TextIOWrapper(p.stdout, encoding='utf8')
while something:
char = reader.read(1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5222 次 |
| 最近记录: |