Python Avro DataFileReader需要一个可查找的文件
问题是stdin不支持avro所需的seek,所以我们将所有内容读取到buffer,然后将其提供给avro_包装器。它在Python2中工作,但在Python3中不工作。我尝试了一些解决方案,但没有一个有效Python Avro DataFileReader需要一个可查找的文件,python,python-3.x,avro,Python,Python 3.x,Avro,问题是stdin不支持avro所需的seek,所以我们将所有内容读取到buffer,然后将其提供给avro_包装器。它在Python2中工作,但在Python3中不工作。我尝试了一些解决方案,但没有一个有效 # stdin doesn't support seek which is needed by avro... so this hack worked in python 2. This does not work in Python 3. # Reading everything to
# stdin doesn't support seek which is needed by avro... so this hack worked in python 2. This does not work in Python 3.
# Reading everything to buffer and then giving this to avro_wrapper.
buf = StringIO()
buf.write(args.input_file.read())
r = DataFileReader(buf, DatumReader())
# Very first record the headers information. Which gives the header names in order along with munge header names for all the record types
# For e.g if we have 2 ports then it will hold the header information of
# 1. port1 on name1 key
# 2. port2 on name2 key and so on
headers_record = next(r)['headers']
上面生成的UnicodeDecodeError:“utf-8”编解码器无法解码位置17中的字节0xf0:无效的继续字节错误
然后我们试着这样做:
input_stream = io.TextIOWrapper(args.input_file.buffer, encoding='latin-1')
sio = io.StringIO(input_stream.read())
r = DataFileReader(sio, DatumReader())
headers_record = next(r)['headers']
这将生成avro.schema.AvroException:不是avro数据文件:Obj与b'Obj\x01不匹配。
错误
另一种方式:
input_stream = io.TextIOWrapper(args.input_file.buffer, encoding='latin-1')
buf = io.BytesIO(input_stream.read().encode('latin-1'))
r = DataFileReader(buf.read(), DatumReader())
headers_record = next(r)['headers']
这将产生AttributeError:'bytes'对象没有属性“seek”错误。
io.BytesIO()
是用于创建包含二进制数据的可在内存文件中查找的对象的正确类型
但是,您犯了一个错误:从io.BytesIO()
文件对象中读取bytes
数据,然后将这些数据而不是实际的文件对象传入
不读取,传入实际的io.BytesIO
文件对象以及从stdin
读取的二进制数据:
buf = io.BytesIO(args.input_file.buffer.read())
r = DataFileReader(buf, DatumReader())
我直接传入了
args.input_文件.buffer
数据,假设args.input
是解码stdin字节的TextIOWrapper
实例,而.buffer
是提供原始二进制数据的底层BufferedReader
实例。将此数据解码为拉丁文1没有意义,那么再次以拉丁语-1编码。只需传递字节。尝试使用二进制文件。或者使用ascii编码为什么要读取io.BytesIO()
缓冲区?stdin
不是您的问题;它是绑定到stdin
的任何对象。另外,对象的类型是args.input\u文件。read()
在Python3上返回?可能是字节
,或者在io.TextIOWrapper()中包装它时会出现不同的错误
object.谢谢,@Martijn Pieters这真的很有帮助。我被这么多不同的尝试分散了注意力,以至于错过了这个相当明显的错误。我还安装了avro-python3 1.8.2。为了调试的目的,我对源代码做了一些修改,这可能导致了一些干扰。我还重新安装了它,并且您的修复程序正在运行。再次感谢您!