Python:通过字符串中的名称访问结构字段

时间:2013-04-17 12:54:57

标签: python ip structure field scapy

在Scapy中,我想比较任意两个数据包ab之间的多个标头字段。这个字段列表是预定义的,例如:

fieldsToCompare = ['tos', 'id', 'len', 'proto'] #IP header

通常我会单独做:

if a[IP].tos == b[IP].tos:
   ... do stuff...

有没有办法从字符串列表中访问这些数据包字段,包括调用每个字符串的内容?像:

for field in fieldsToCompare:
    if a[IP].field == b[IP].field:
         ... do stuff...

2 个答案:

答案 0 :(得分:16)

您可以使用getattr()。这些行是等价的:

getattr(x, 'foobar')
x.foobar

setattr()是它的对手。

答案 1 :(得分:3)

我认为你正在寻找getattr()。尝试...

for field in fieldsToCompare:
    if getattr(a[IP], field) == getattr(b[IP], field):
         ... do stuff...