Python: access structure field through its name in

2019-06-18 02:57发布

问题:

In Scapy, I want to compare a number of header fields between any two packets a and b. This list of fields is predefined, say:

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

Normally I would do it individually:

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

Is there any way to access those packet fields from a list of strings including what each one of them is called? Like:

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

回答1:

You can use getattr(). These lines are equivalent:

getattr(x, 'foobar')
x.foobar

setattr() is its counterpart.



回答2:

I think you're looking for getattr(). Try...

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