当代码被放入函数时 a 是未定义的

a is undefined when code is put into a function

我有一个 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())

它returns:

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

您收到错误消息是因为没有全局变量 a

有几个选项:

  • 在所有函数之外声明 a 使其成为 global
  • 在函数 f() 中,从 a 中删除 global 并用值对其进行初始化,使其成为局部变量。
  • 如果你仍然想在外部函数中使用变量 a,那么在访问时删除 global 关键字并将其设为 mutable