【问题标题】:Python: access structure field through its name in a stringPython:通过字符串中的名称访问结构字段
【发布时间】:2023-03-17 07:33:01
【问题描述】:

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

【问题讨论】:

    标签: python ip structure field scapy


    【解决方案1】:

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

    getattr(x, 'foobar')
    x.foobar
    

    setattr() 是它的对应物。

    【讨论】:

      【解决方案2】:

      我认为您正在寻找getattr()。试试……

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

      【讨论】:

        猜你喜欢
        • 2022-07-22
        • 2016-07-30
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 2021-02-10
        • 1970-01-01
        相关资源
        最近更新 更多