Linux 固定属性错误:';文件';对象没有属性';缓冲区';(蟒蛇3)
Ubuntu上的Python 2.7。我尝试为Python3运行小型python脚本(文件转换器),出现错误:Linux 固定属性错误:';文件';对象没有属性';缓冲区';(蟒蛇3),linux,python-3.x,python-2.7,type-conversion,Linux,Python 3.x,Python 2.7,Type Conversion,Ubuntu上的Python 2.7。我尝试为Python3运行小型python脚本(文件转换器),出现错误: $ python uboot_mdb_to_image.py < input.txt > output.bin Traceback (most recent call last): File "uboot_mdb_to_image.py", line 29, in <module> ascii_stdin = io.TextIOWrapper(sys
$ python uboot_mdb_to_image.py < input.txt > output.bin
Traceback (most recent call last):
File "uboot_mdb_to_image.py", line 29, in <module>
ascii_stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='ascii', errors='strict')
AttributeError: 'file' object has no attribute 'buffer'
有人能给我建议如何解决这个问题吗?这是一个老问题,但由于我遇到了类似的问题,在谷歌搜索错误时首先出现了这个问题 是的,这是由Python3和Python2之间的差异引起的。在Python3中,
sys.stdin
被包装在io.TextIOWrapper
中。在Python 2中,它是一个文件
对象,没有缓冲区
属性。这同样适用于stderr
和stdout
在这种情况下,可以使用编解码器
标准库实现Python 2中的相同功能:
ascii_stdin = codecs.getreader("ascii")(sys.stdin, errors="strict")
但是,此代码段提供的是codecs.StreamReader
,而不是io.TextIOWrapper
,因此可能不适用于其他情况。而且,不幸的是,在io.TextIOWrapper
中包装Python2stdin并不是一件小事——有关这方面的更多讨论,请参阅
这个脚本有更多的Python 2不兼容之处。与所讨论的问题相关,sys.stdout
没有buffer
属性,因此最后一行应该是
sys.stdout.write(data)
其他我能发现的东西:
没有str.split
参数。使用maxslit
代替line.split(“”[:2]
没有int
属性。但是from\u bytes
似乎是等效的int(straddr[:-1].encode('hex'),16)
类型仅为Python 3。在Python 2中,它是字节
的别名str
sys.stdout.write(data)