这个函数如何知道变量存在?

我有一些代码:


from scapy.all import *


def sniffFunc(pkt):

    print(pkt.show())

    quit()


myFilter = 'tcp and src host 192.168.1.2 and dst host 52.223.224.41'

sniff(filter=myFilter, prn=sniffFunc)

它从我的主机嗅探单个数据包到 twitch 服务器并显示该数据包的信息。sniffFunc() 如何知道变量“pkt”是什么以及该变量的值?我知道名称可以是程序员想要的关于传递给函数的变量的任何名称,但是,一旦进入函数内部,在我看来变量“pkt”将为空,但它包含所需的值。例如,我认为人们必须做类似的事情:


pkt = sniff(filter=myFilter, prn=sniffFunc(pkt))

虽然这行不通,但也许它会让我对我的思维过程有一些了解。


呼啦一阵风
浏览 108回答 1
1回答

繁星coding

函数本身可以保存到变量中,然后调用:f&nbsp;=&nbsp;sniffFunc f(a_packet)&nbsp;&nbsp;#&nbsp;Still&nbsp;works被调用的函数对象sniffFunc会像任何其他对象一样传递给该函数。一旦进入sniff(实际上在代码的深处),它会获取您提供的函数对象,并通过向其传递给定的数据包来调用它:def on_packet_received(self, pkt):&nbsp; &nbsp; """DEV: entry point. Will be called by sniff() for each&nbsp; &nbsp; received packet (that passes the filters).&nbsp; &nbsp; """&nbsp; &nbsp; if not pkt:&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; if isinstance(pkt, list):&nbsp; &nbsp; &nbsp; &nbsp; for p in pkt:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; DefaultSession.on_packet_received(self, p)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; self.__count += 1&nbsp; &nbsp; if self.store:&nbsp; &nbsp; &nbsp; &nbsp; self.lst.append(pkt)&nbsp; &nbsp; if self.prn:&nbsp; &nbsp; &nbsp; &nbsp; result = self.prn(pkt)&nbsp; # Your function was stored in the variable self.prn <<<<<&nbsp; &nbsp; &nbsp; &nbsp; if result is not None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(result)result是你的函数返回的任何内容。你可以看到它只是打印返回值(如果有的话)。
打开App,查看更多内容
随时随地看视频慕课网APP