- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试运行这个:
def ReadWord(fid,fmt,Addr):
fid.seek(Addr)
s = fid.readline(2)
s = unpack(fmt + 'h', s)
if(type(s) == tuple):
return s[0]
else:
return s
与:
len(s) = 2
len(fmt) = 1
calcsize(fmt) = 0
calcsize(fmt + 'h') = 2
但是,Python 返回:
struct.error: unpack requires a string argument of length 4
根据 python struct.unpack
documentation :
The string must contain exactly the amount of data required by the format (len(string) must equal calcsize(fmt)).
因此,如果我的字符串的长度为 2 且计算大小为 fmt+'h'
也是2,为什么python说“解包需要长度为4的字符串参数”??
编辑:
感谢您的所有回答。这是完整的代码:
http://qtwork.tudelft.nl/gitdata/users/guen/qtlabanalysis/analysis_modules/general/lecroy.py
正如您在 read_timetrace
中看到的那样功能,fmt
设置为 '<'
或 '>'
在if...else
陈述。打印它可以确认这一点。
但是您还应该知道我正在使用 windowsx64(工作)。
EDIT2
这是完整的回溯,对错误感到抱歉。
Traceback (most recent call last):
File "C:\Users\maxime.vast\Desktop\Test Campaign Template\Test Suite\Include\readLecroyTRCFile.py", line 139, in <module>
read_timetrace("C:\Users\maxime.vast\Desktop\Test Campaign Template\Test Suite\Traces\KL.ES.001.001.trc")
File "C:\Users\maxime.vast\Desktop\Test Campaign Template\Test Suite\Include\readLecroyTRCFile.py", line 60, in read_timetrace
WAVE_ARRAY_1 = ReadLong(fid, fmt, aWAVE_ARRAY_1)
File "C:\Users\maxime.vast\Desktop\Test Campaign Template\Test Suite\Include\readLecroyTRCFile.py", line 100, in ReadLong
s = unpack(fmt + 'l', s)
struct.error: unpack requires a string argument of length 4
[Finished in 0.2s]
编辑 3:
我替换了readline
通过 read
并添加:
print "len(s) ", len(s)
print "len(fmt) ", len(fmt)
print "calcsize(fmt) ", calcsize(fmt)
print "calcsize(fmt + 'h') ", calcsize(fmt + 'h')
print "fmt ", fmt
到ReadLong
功能。
这是新的追溯:
len(s) 4
len(fmt) 1
calcsize(fmt) 0
calcsize(fmt + 'h') 2
fmt <
len(s) 4
len(fmt) 1
calcsize(fmt) 0
calcsize(fmt + 'h') 2
fmt <
len(s) 4
len(fmt) 1
calcsize(fmt) 0
calcsize(fmt + 'h') 2
fmt <
len(s) 1
len(fmt) 1
calcsize(fmt) 0
calcsize(fmt + 'h') 2
fmt <
Traceback (most recent call last):
File "C:\Users\maxime.vast\Desktop\Test Campaign Template\Test Suite\Include\readLecroyTRCFile.py", line 143, in <module>
read_timetrace("C:\Users\maxime.vast\Desktop\Test Campaign Template\Test Suite\Traces\KL.ES.001.001.trc")
File "C:\Users\maxime.vast\Desktop\Test Campaign Template\Test Suite\Include\readLecroyTRCFile.py", line 60, in read_timetrace
WAVE_ARRAY_1 = ReadLong(fid, fmt, aWAVE_ARRAY_1)
File "C:\Users\maxime.vast\Desktop\Test Campaign Template\Test Suite\Include\readLecroyTRCFile.py", line 104, in ReadLong
s = unpack(fmt + 'l', s)
struct.error: unpack requires a string argument of length 4
[Finished in 0.2s]
最佳答案
FWIW,您应该使用 read(2)
,而不是 readline(2)
。如果 fmt
字符串确实是 '>'
,您就不会收到该错误。这是一个按预期执行的简短演示。
from struct import unpack
fname = 'qbytes'
#Create a file of all byte values
with open(fname, 'wb') as f:
f.write(bytearray(range(256)))
def ReadWord(fid, fmt, addr):
fid.seek(addr)
s = fid.read(2)
s = unpack(fmt + 'h', s)
return s[0]
fid = open(fname, 'rb')
for i in range(16):
addr = i
n = 256*i + i+1
#Interpret file data as big-endian
print i, ReadWord(fid, '>', addr), n
fid.close()
输出
0 1 1
1 258 258
2 515 515
3 772 772
4 1029 1029
5 1286 1286
6 1543 1543
7 1800 1800
8 2057 2057
9 2314 2314
10 2571 2571
11 2828 2828
12 3085 3085
13 3342 3342
14 3599 3599
15 3856 3856
顺便说一句,struct.unpack()
总是返回一个元组,即使返回值是单个项目也是如此。
对二进制文件使用 readline(2)
会产生意想不到的结果。在我上面代码的测试文件中,文件中有一个(Linux 风格的)换行符 \xa0
。因此,如果您将 s = fid.read(2)
更改为 s = fid.readline(2)
一开始一切正常,但在第 10 行它崩溃了,因为它只由于换行符,读取单个字节:
from struct import unpack
fname = 'qbytes'
#Create a file of all byte values
with open(fname, 'wb') as f:
f.write(bytearray(range(256)))
def ReadWord(fid, fmt, addr):
fid.seek(addr)
s = fid.readline(2)
print repr(s),
s = unpack(fmt + 'h', s)
return s[0]
with open(fname, 'rb') as fid:
for i in range(16):
addr = i
n = 256*i + i+1
#Interpret file data as big-endian
print i, ReadWord(fid, '>', addr), n
输出
0 '\x00\x01' 1 1
1 '\x01\x02' 258 258
2 '\x02\x03' 515 515
3 '\x03\x04' 772 772
4 '\x04\x05' 1029 1029
5 '\x05\x06' 1286 1286
6 '\x06\x07' 1543 1543
7 '\x07\x08' 1800 1800
8 '\x08\t' 2057 2057
9 '\t\n' 2314 2314
10 '\n'
Traceback (most recent call last):
File "./qtest.py", line 30, in <module>
print i, ReadWord(fid, '>', addr), n
File "./qtest.py", line 22, in ReadWord
s = unpack(fmt + 'h', s)
struct.error: unpack requires a string argument of length 2
您的代码中有几个函数几乎做同样的事情。这打破了 DRY原则:不要重复自己。这是解决该问题的一种方法,使用部分函数应用程序。查看functools docs了解更多信息。
from functools import partial
def ReadNumber(fid, datalen=1, fmt='>', conv='b', addr=0):
fid.seek(addr)
s = fid.read(datalen)
if len(s) != datalen:
raise IOError('Read %d bytes but expected %d at %d' % (len(s), datalen, addr))
return unpack(fmt+conv, s)[0]
ReadByte = partial(ReadNumber, datalen=1, conv='b')
ReadWord = partial(ReadNumber, datalen=2, conv='h')
ReadLong = partial(ReadNumber, datalen=4, conv='l')
ReadFloat = partial(ReadNumber, datalen=4, conv='f')
ReadDouble = partial(ReadNumber, datalen=8, conv='d')
您需要使用关键字来调用这些新功能。例如,
ReadLong(fid, fmt='>', addr=addr)
的确,这有点冗长,但它使代码更具可读性。
关于Python struct.unpack 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32519664/
我有一个数组 items[] items[] 中的每一项都是一个结构体。 item 有键 id、date、value(即 item.id、item.date、item.value) 我想使用 Stru
我想存储 100 名员工。 RollNo,姓名,工资,时间(各种数据,我无法在这里解释,但你可以看下面的代码片段来理解 main() { struct day { int hour
这个问题在这里已经有了答案: storage size of ‘names’ isn’t known (3 个答案) 关闭 5 年前。 我正在尝试蓝牙编程,遇到了这个我不明白的问题。基本上,当我使用
这是一个奇怪的事情: 我有一个结构,它包含指向相同类型结构的指针和指向其他类型结构的指针,以及一些其他值。 struct animal { struct animal * father;
我有一个结构定义如下(名称不同) struct str1 { int field1; struct str2; } 我在一个函数中有一个*str1。我想要一个指向 str2 的指针。 所以
DISK_DETECTION_INFO is defined as有什么原因吗? typedef struct _DISK_DETECTION_INFO { DWORD Size
我正在尝试打包一个字符串和一个字符串的长度。 fmt = '
我在创建结构时遇到问题。 我的结构: public struct Device: Codable { let data: DeviceData let meta: Meta? } pu
struct Item { var name:String? var type:String? var value:Int? var tag:Int? } ... ..
// NewReaderSize returns a new Reader whose buffer has at least the specified 43 // size. If the ar
这个问题在这里已经有了答案: Sorting a vector of custom objects (14 个答案) 关闭 3 年前。 在下面的 C++ 片段中, 如何基于 TwoInts 结构中的
#include struct Header { unsigned long long int alignment; }; int main(void) { struct Heade
我有一个目前看起来像这样的结构(缩写为仅显示基本部分): typedef struct { uint32_t baudrate; ... some other internally u
对此没有太多解释,这就是我所拥有的: public struct PACKET_HEADER { public string computerIp; publi
我有以下代码: struct MyStruct{ data: &'a str, } fn get(S: &'a MyStruct) -> &'a str{ S.data } fn se
struct S1 { char c; int i; }; struct S3 { char c1; struct S1 s; double c2; }; 我正
我有一个名为 Parameter 的协议(protocol): protocol Parameter { var name: String { get } var unit: Unit
有 2 个 struct 定义 A 和 A。我知道 struct A 可以包含指向 struct A 的 POINTER 但我不明白为什么 struct A 不能包含struct A(不是指针) 最佳
我有以下代码: struct MyStruct{ data: &'a str, } fn get(S: &'a MyStruct) -> &'a str{ S.data } fn se
为了说明这一点,这里有一个小的不可变结构和一个更新它的函数: (struct timeseries (variable observations) #:transparent) (define (ad
我是一名优秀的程序员,十分优秀!