通过使用curio库,我开始熟悉Python中新的async/await语法。在
总体概念很容易理解,但现在我遇到了一个问题,我需要将通过回调函数接收的结果传输到异步环境中。在
在这个项目中,我使用scapy库来捕获网络数据包,我想实时接收和处理这些数据包。这就是为什么我只能使用回调,不能期望函数的异步变体。在
在我目前的方法中,我试图通过古董自己的队列来处理这个问题。但由于我是在同步环境中调用异步操作,所以我将队列的put函数包装在古董跑(队列.put(数据))。数据按预期被传送到接收器,但只有在线程完成之后。在
捕获数据包的代码如下所示:
from scapy.all import sniff
from functools import partial
def async_receiver_wrapper(queue, pkt):
# curio.run(queue.put(pkt))
try:
print("callback: " + pkt.summary())
queue.put(pkt).send(None)
except StopIteration:
pass
async def capture(pkt_queue, ev, timeout=None, count=0):
on_rx = partial(receiver, pkt_queue, ev)
sniff(iface="eth0", prn=on_rx, timeout=timeout, count=count, store=0)
调用代码如下所示:
^{pr2}$此代码的结果输出是:
Callback: Ether / ARP who has 10.0.0.15 says 10.0.0.1
Callback: Ether / ARP is at xx:xx:xx:xx:xx:xx says 10.0.0.15
Callback: Ether / IP / TCP ... PA / Raw
Callback: Ether / IP / TCP ... PA / Raw
Callback: Ether / IP / TCP ... FPA / Raw
...
Received: Ether / ARP who has 10.0.0.15 says 10.0.0.1
Received: Ether / ARP is at xx:xx:xx:xx:xx:xx says 10.0.0.15
Received: Ether / IP / TCP ... PA / Raw
Received: Ether / IP / TCP ... PA / Raw
Received: Ether / IP / TCP ... FPA / Raw
...
但我希望是这样
Callback: Ether / ARP who has 10.0.0.15 says 10.0.0.1
Received: Ether / ARP who has 10.0.0.15 says 10.0.0.1
Callback: Ether / ARP is at xx:xx:xx:xx:xx:xx says 10.0.0.15
Received: Ether / ARP is at xx:xx:xx:xx:xx:xx says 10.0.0.15
Callback: Ether / IP / TCP ... PA / Raw
Received: Ether / IP / TCP ... PA / Raw
Callback: Ether / IP / TCP ... PA / Raw
Received: Ether / IP / TCP ... PA / Raw
Callback: Ether / IP / TCP ... FPA / Raw
Received: Ether / IP / TCP ... FPA / Raw
...
正如在片段中可以看到的,我已经尝试过使用原始队列,它应该用于在另一个线程和异步之间进行同步。任务。在
目前没有回答
相关问题 更多 >
编程相关推荐