我有一段代码可以打开并读取二进制文件。with open (file, mode="rb") as myfile: message_string=myfile.read() myfile.close 现在我需要从stdin中读取相同的内容,但我无法弄清如何读取二进制数据。 错误显示只接受字节串。 有什么建议吗?
在Python 3中,如果您想从stdin读取二进制数据,则需要使用其buffer属性: import sys data = sys.stdin.buffer.read() 在Python 2中,sys.stdin.read()已经返回了一个字节字符串;没有必要使用buffer。
$ printf "a\r\nb\rc\r" | python2.7 -c 'import sys; print(sys.stdin.readlines())'
将会生成['a\r\n', 'b\rc\r']
。 - Clément$
表示你没有在Windows上运行它。(除非你正在使用Windows子系统来运行Linux,但对于这些目的,我们可以认为它不是Windows。) - icktoofay