python - 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也很陌生,所以请执行我的菜鸟提问技巧
解决方案
在 python 3.x 中,你必须添加 bytes(your bytes).encode 而不是之前的 2.x 格式。它成为了
test = fmt.unpack_from(bytes(''.join('\0' for i in range(fmt.size)).encode()))
推荐阅读
- python - pca.fit(X) return Error ValueError: setting an array element with a sequence
- wpf - x:Name 导致编译失败。没有它不会
- python - 如何在机器学习中处理人体姿势坐标以生成序列?
- html - 输入按钮上的 line-height 仅适用于 Chrome/Safari 上的边框
- javascript - 如何从nodejs调用外部api
- python - Django:如何忽略 Celery 的任务?
- javascript - 如何使用脚本将“节点形状更改为气泡”和更改“子间隙”?
- css - 如何通过负边距消除堆叠的内联块元素的“双边框”?
- python - Python Selenium - 在网页上查找动态单词
- python - 在单个 DataFrame 中查找子行而不使用循环