![](/img/trans.png)
[英]How to pass a variable as an argument to a function if the variable exists
[英]How does this function know the variable exists?
我有一些代碼:
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))
雖然這行不通,但也許它會讓我對我的思考過程有所了解。
函數本身可以保存到變量中,然后調用:
f = sniffFunc
f(a_packet) # Still works
名為sniffFunc
的函數對象像任何其他對象一樣被傳遞給函數。 一旦進入sniff
( 實際上在代碼內部很深),它就會獲取你給它的函數對象,並通過傳遞給它的數據包來調用它:
def on_packet_received(self, pkt):
"""DEV: entry point. Will be called by sniff() for each
received packet (that passes the filters).
"""
if not pkt:
return
if isinstance(pkt, list):
for p in pkt:
DefaultSession.on_packet_received(self, p)
return
self.__count += 1
if self.store:
self.lst.append(pkt)
if self.prn:
result = self.prn(pkt) # Your function was stored in the variable self.prn <<<<<
if result is not None:
print(result)
result
是您的函數返回的任何內容。 您可以看到它只打印返回值(如果有)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.