Python - 如何停止一个函数

问题描述 投票:0回答:1

我正在尝试做某种会话启动协议嗅探器。我正在使用pyshark模块进行python,它为我提供了一些从接口嗅探数据包的功能。问题在于有一个名为sniff()的函数,当我给出一个参数packet_count=0时,它会无限期地检查数据包,直到我停止整个程序。

我想知道是否有办法停止cap.sniff()函数并检索cap._packets(这是一个列表),然后让程序的其余部分运行。

这是我制作的代码:

def sniffsip():
    cap = pyshark.LiveCapture(interface='Ethernet')
    cap.sniff(packet_count=0)#This is function sniff() that checks for packets

    udp_packets = []

    for i in cap._packets:
        j = cap._packets.index(i)
        if cap._packets[j].transport_layer == 'UDP' and cap._packets[j].highest_layer == 'SIP':
            udp_packets.append(cap._packets[j])

    return udp_packets
python function sip
1个回答
0
投票

我想你只想打破那个循环。

stop_flag = False # It is a global variable, you can set it in other functions

def sniffsip():
    global stop_flag # Our global variable...
    cap = pyshark.LiveCapture(interface='Ethernet')
    cap.sniff(packet_count=0)

    udp_packets = []

    for i in cap._packets:
        j = cap._packets.index(i)
        if cap._packets[j].transport_layer == 'UDP' and cap._packets[j].highest_layer == 'SIP':
            udp_packets.append(cap._packets[j])
        if stop_flag: # Here check the state of the flag
           stop_flag = False # Do not forget to set it false if you want to use the function again.
           break # Break the cycle

    return udp_packets
© www.soinside.com 2019 - 2024. All rights reserved.