【问题标题】:UnicodeDecodeError in Python3 when reading binary files stdin读取二进制文件stdin时Python3中的UnicodeDecodeError
【发布时间】:2017-03-12 16:51:28
【问题描述】:

我正在尝试获取标准输入中的内容并一次读取 1022 个字节。此代码适用于文本文件。但是当输入一个二进制文件时,它给了我 UnicodeDecodeError。下面的数据是 sys.stdin。

def sendStdIn(conn, cipher, data):
    while True:
        chunk = data.read(1022)
        if len(chunk)==1022:
            EOFAndChunk = b'F' + chunk.encode("utf-8")
            conn.send(encryptAndPad(cipher,EOFAndChunk))
        else:
            EOFAndChunk = b'T' + chunk.encode("utf-8")
            conn.send(encryptAndPad(cipher,EOFAndChunk))
            break
    return True

二进制文件是通过调用dd if=/dev/urandom bs=1K iflag=fullblock count=1K > 1MB.bin生成的

我基本上使用python A3C.py < 1MB.bin 运行该文件 然后我在下面结束。

Traceback (most recent call last):
  File "A3C.py", line 163, in <module>
    main()
  File "A3C.py", line 121, in main
    EasyCrypto.sendStdIn(soc, cipher, sys.stdin)
  File "EasyCrypto.py", line 63, in sendStdIn
    chunk = data.read(1022)
  File "/usr/lib64/python3.5/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe8 in position 0: invalid continuation byte

知道如何制作它,以便它可以读取二进制文件的各个部分,因为我需要一次将它们从这个客户端发送到服务器端。谢谢!

【问题讨论】:

  • 解决方法是在main() 中编码,而不是在sendStdIn 中。幸好你包含了完整的回溯! :-)

标签: python python-3.x stdin


【解决方案1】:

sys.stdin 是一个解码二进制数据的文本包装器。请改用sys.stdin.buffer

EasyCrypto.sendStdIn(soc, cipher, sys.stdin.buffer)

TextIOBase.buffer attribute 指向下面的二进制缓冲 I/O 对象。

【讨论】:

  • 非常感谢!这非常有效。这让我发疯了。
猜你喜欢
  • 2018-12-25
  • 2019-09-25
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
相关资源
最近更新 更多