我有一个scapy嗅探器,它不在以下函数中时运行良好:
from scapy.all import *
a = 0
def f(packet):
global a
a+=1
s = sniff(prn=f, timeout=1, iface='en0', store=0)
print(a)
但是当我将代码放入这样的函数中时:
from scapy.all import *
def sniffer():
a = 0
def f(packet):
global a
a+=1
s = sniff(prn=f, timeout=1, iface='en0', store=0)
return a
print(sniffer())
它返回:
File "/Users/test.py", line 9, in f
a+=1
NameError: name 'a' is not defined
似乎可以解决此问题,所以我将不胜感激。
a
不是全局变量,因为它是在sniffer()
函数内部定义的。做你想做的事,你应该使用nonlocal
而不是global
:
from scapy.all import *
def sniffer():
a = 0
def f(packet):
nonlocal a
a+=1
s = sniff(prn=f, timeout=1, iface='en0', store=0)
return a
print(sniffer())
有关该nonlocal
声明的更多信息:https ://docs.python.org/3/reference/simple_stmts.html ? highlight = nonlocal# the- nonlocal-statement 。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句