读取二进制文件stdin时Python3中的UnicodeDecodeError

时间:2017-03-12 16:51:28

标签: python python-3.x stdin

我正在尝试获取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

任何想法我怎么能这样做它所以它可以读取二进制文件的部分,因为我需要一次从这个客户端发送到服务器端。谢谢!

1 个答案:

答案 0 :(得分:3)

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

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

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