linux – 修复AttributeError:’file’对象没有属性’buffer'(Python3)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了linux – 修复AttributeError:’file’对象没有属性’buffer'(Python3),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2428字,纯文字阅读大概需要4分钟。
内容图文
![linux – 修复AttributeError:’file’对象没有属性’buffer](/upload/InfoBanner/zyjiaocheng/963/8f29df7a8e0747c197abd564ac49eed9.jpg)
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.stdin.buffer, encoding='ascii', errors='strict')
AttributeError: 'file' object has no attribute 'buffer'
我怀疑它是由python 3和python 2之间的语法差异引起的,这里是脚本本身:
#!/usr/bin/env python3
import sys
import io
BYTES_IN_LINE = 0x10 # Number of bytes to expect in each line
c_addr = None
hex_to_ch = {}
ascii_stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='ascii', errors='strict')
for line in ascii_stdin:
line = line[:-1] # Strip the linefeed (we can't strip all white
# space here, think of a line of 0x20s)
data, ascii_data = line.split(" ", maxsplit = 1)
straddr, strdata = data.split(maxsplit = 1)
addr = int.from_bytes(bytes.fromhex(straddr[:-1]), byteorder = 'big')
if c_addr != addr - BYTES_IN_LINE:
if c_addr:
sys.exit("Unexpected c_addr in line: '%s'" % line)
c_addr = addr
data = bytes.fromhex(strdata)
if len(data) != BYTES_IN_LINE:
sys.exit("Unexpected number of bytes in line: '%s'" % line)
# Verify that the mapping from hex data to ASCII is consistent (sanity check for transmission errors)
for b, c in zip(data, ascii_data):
try:
if hex_to_ch[b] != c:
sys.exit("Inconsistency between hex data and ASCII data in line (or the lines before): '%s'" % line)
except KeyError:
hex_to_ch[b] = c
sys.stdout.buffer.write(data)
任何人都可以建议如何解决这个问题吗?
解决方法:
这是一个老问题,但是因为我遇到了类似的问题,所以当谷歌搜索错误时它首先出现了……
是的,它是由Python 3和2之间的差异引起的.在Python 3中,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中包装Python 2 stdin并非易事 – 请参阅Wrap an open stream with io.TextIOWrapper以获得更多讨论.
有问题的脚本有更多的Python 2不可兼容性.与相关问题相关,sys.stdout没有缓冲区属性,因此最后一行应该是
sys.stdout.write(data)
我能发现的其他事情:
> str.split没有maxsplit参数.请改用line.split(“”)[:2].
> int没有from_bytes属性.但int(straddr [: – 1] .encode(‘hex’),16)似乎是等价的.
> bytes类型仅限Python 3.在Python 2中,它是str的别名.
内容总结
以上是互联网集市为您收集整理的linux – 修复AttributeError:’file’对象没有属性’buffer'(Python3)全部内容,希望文章能够帮你解决linux – 修复AttributeError:’file’对象没有属性’buffer'(Python3)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。