我用threading.Thread起了个线程跑sniff,想让它正常停止,该怎么做
时间: 2023-08-21 11:01:54 浏览: 38
可以在主线程中设置一个标志位,当需要停止线程时,将标志位置为True,并在线程中定期检查该标志位的值,如果为True,则退出线程。具体实现可以参考以下代码:
```python
import threading
import time
from scapy.all import *
class SnifferThread(threading.Thread):
def __init__(self):
super().__init__()
self.stop_flag = False
def run(self):
while not self.stop_flag:
sniff(count=1, filter="icmp", prn=lambda x: x.summary())
def stop(self):
self.stop_flag = True
if __name__ == "__main__":
sniffer_thread = SnifferThread()
sniffer_thread.start()
time.sleep(10) # 运行10秒后停止线程
sniffer_thread.stop()
sniffer_thread.join()
```
在上面的代码中,SnifferThread类继承自threading.Thread类,并且定义了一个stop_flag标志位。在run方法中,循环检测stop_flag的值,如果为True则退出循环。在主线程中,创建SnifferThread对象并启动它,然后等待10秒后调用stop方法停止线程,并调用join方法等待线程结束。这样可以保证线程能够正常停止。