Python中的多进程与并行性

2024-10-01 07:45:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python脚本,它使用scapy进行一些包嗅探和解析。所有这些都很好地工作,我决定尝试将其作为多线程脚本来处理更大的流量。在

基本思想是,如果scapy看到一个有趣的包,将其放入队列中,让所有的工作人员从队列中取出一个包,处理它,然后返回到另一个包。这个循环只运行一次,所以我猜当脚本回到事情的边缘时,它不会松懈。在

如何才能使scapy继续向队列中抛出数据包,而我的线程可以继续处理队列中的数据包?在

from scapy.all import *
from Queue import Queue
from threading import Thread
max_threads=10

packetqueue=Queue(maxsize=0)

def queue_packet(packet):
        packetqueue.put(packet)

def analyze_packet(q):
        while True:
                packet=q.get()
                <do stuff to packet>
                q.task_done()

for i in range(max_threads):
        worker=Thread(target=analyze_packet,args=(packetqueue,))
        worker.setDaemon(True)
        worker.start()

sniff(iface="eth4", filter = "<filter>", store=0, prn=queue_packet)

Tags: fromimport脚本队列queuepacketdef数据包