【发布时间】: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