Python: access structure field through its name in a string

不想你离开。 提交于 2020-01-14 07:58:12

问题


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...


来源:https://stackoverflow.com/questions/16060625/python-access-structure-field-through-its-name-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!