由于这段代码,我试图在我的列表中放入一组数据但是info_hash有一些问题:
handshake = piece_request_handshake.findall(hex_data)
match = piece_request_handshake.match(hex_data)
info_hash = match.group('info_hash')
# If the packet is a packet type handshake, if the dest and src ip are not in the list "liste" and if the handshake is not empty, then we add the adress src and dest to the list
if handshake and (src_ip+" "+dst_ip+" "+info_hash) not in liste and (dst_ip+" "+src_ip+" "+info_hash) not in liste and handshake != '':
liste.append(src_ip+" "+dst_ip+" "+info_hash)
但我不知道为什么它会给我这个错误:
root@debian:/home/florian/Documents/mysite/polls# python scriptbdd.py
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
self.run()
File "scriptbdd.py", line 134, in run
self.p.dispatch(0, PieceRequestSniffer.cb)
File "scriptbdd.py", line 80, in cb
info_hash = match.group('info_hash')
AttributeError: 'NoneType' object has no attribute 'group'
我真的不明白如何在经过多次尝试后才能解决这个问题,请求您的帮助。
答案 0 :(得分:2)
因为你的正则表达式引擎找不到匹配项所以它返回None
并且你试图得到它的group
。为了获得它,您可以使用try-except
:
handshake = piece_request_handshake.findall(hex_data)
match = piece_request_handshake.match(hex_data)
try :
info_hash = match.group('info_hash')
# If the packet is a packet type handshake, if the dest and src ip are not in the list "liste" and if the handshake is not empty, then we add the adress src and dest to the list
if info_hash and handshake and (src_ip+" "+dst_ip+" "+info_hash) not in liste and (dst_ip+" "+src_ip+" "+info_hash) not in liste and handshake != '':
liste.append(src_ip+" "+dst_ip+" "+info_hash)
except AttributeError:
print 'there is no match'
答案 1 :(得分:1)
It's quite obvious:如果表达式与字符串不匹配,则re.match()
会返回None
,None
没有属性group
。在执行任何操作之前,您必须检查re.match()
的返回值:
match = piece_request_handshake.match(hex_data)
if match is not None:
info_hash = match.group('info_hash')
# etc
else:
# do whatever else
print "didn't match"