读取二进制文件标准输入时 Python3 中的 UnicodeDecodeError

UnicodeDecodeError in Python3 when reading binary files stdin

我正在尝试获取标准输入中的内容并一次读取 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

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

sys.stdin 是一个解码二进制数据的文本包装器。使用 sys.stdin.buffer 代替:

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

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