带有bytearray的struct.unpack [英] struct.unpack with bytearray's

查看:141
本文介绍了带有bytearray的struct.unpack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个在字节数组上使用struct.unpack的应用程序.使用python 2.7.5在我的机器上运行它,效果很好:

I wrote an application that uses struct.unpack on byte arrays. Running it on my machine using python 2.7.5 it works well:

>>> data
bytearray(b'\x07\x00\x00\x00\x00\x00\x00\x00')
>>> struct.unpack("<Q", data)   
(7,)

但是,我尝试将其与python 2.7.3版一起使用时出现异常:

however, I tried to use it with a python version 2.7.3 I got an exception:

错误:解压缩需要一个长度为8的字符串参数

error: unpack requires a string argument of length 8

在将其解压缩之前,我需要将字节数组显式转换为字符串.这与python版本更改有关吗? 结构手册对此一无所知.铸造,有什么解决方法吗?

I need to explicitly cast the bytearray to string before unpacking it. Is this related to the python version change? the struct manual says nothing about this.. I would like to avoid doing all the casting, is there any way around this?

推荐答案

您已经注意到,这与Python版本有关.显然struct.unpack是在2.7.3版之后修复或扩展的.

As you have noticed, this is related to Python version. Apparently struct.unpack was fixed or extended after version 2.7.3.

如果您的脚本必须同时适用于2.7.5和2.7.3版本,并且您已经找到一种使其在两个版本上都可以运行的方法(通过强制转换为字符串),则可以将变通方法代码与对<的调用一起放置c0>转换为函数并调用此函数,而不是在需要执行的任何地方直接进行struct.unpack的强制转换和调用.这样,您的代码将保持简洁,简短且 DRY .

If your script must work with both version 2.7.5 and 2.7.3 and you have found a way to make it run on both versions (by casting to string) then you can put your workaround code along with the call to struct.unpack into a function and call this function instead of doing directly the casting and calling of struct.unpack wherever you need to do it. This way your code will stay elegant, short and DRY.

这篇关于带有bytearray的struct.unpack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆