首页 > 解决方案 > python,使用 unpack_from 和 fmt

问题描述

嗨,我正在尝试理解一段代码,当我在这里运行它时,这部分代码出现错误。我认为它存在根本性错误,但这可能只是因为没有调用它的输入

from cstruct import struct

class MateNET(object):
"""
Interface for the MATE RJ45 bus ("MateNET")
This class only handles the low level protocol,
it does not care what is attached to the bus.
"""
    TxPacket = struct('>BBHH', ('port', 'ptype', 'addr', 'param'))  #  Payload is always 4 bytes?
    QueryPacket = struct('>HH', ('reg', 'param'))
    QueryResponse = struct('>H', ('value'))

结构函数是

 def struct(fmt, fields):
     fmt = Struct(fmt)
     test = fmt.unpack_from(''.join('\0' for i in range(fmt.size)))
       nfields = len(test)

       if len(fields) != nfields:
             raise RuntimeError("Number of fields provided does not match the struct format (Format: %d, Fields: %d)" % (nfields, len(fields)))

错误是:

Traceback (most recent call last):
  File "C:\pymate\matenet\FX_inverter_controller.py", line 1, in <module>
    from matenet import MateFX
  File "C:\pymate\matenet\matenet.py", line 30, in <module>
    class MateNET(object):
  File "C:\pymate\matenet\matenet.py", line 36, in MateNET
    TxPacket = struct('>BBHH', ('port', 'ptype', 'addr', 'param'))  # Payload is always 4 bytes?
  File "C:\pymate\matenet\cstruct.py", line 14, in struct
    test = fmt.unpack_from(''.join('\0' for i in range(fmt.size)))
TypeError: a bytes-like object is required, not 'str'

我在这里很新,对python也很陌生,所以请执行我的菜鸟提问技巧

标签: pythonstruct

解决方案


在 python 3.x 中,你必须添加 bytes(your bytes).encode 而不是之前的 2.x 格式。它成为了

test = fmt.unpack_from(bytes(''.join('\0' for i in range(fmt.size)).encode()))

推荐阅读