我有一个在远程设备上运行的 python 脚本。将创建两个不同的线程。创建第一个线程以监视与设备的 USB 连接。
class USBDetector(threading.Thread):
''' Monitor udev for detection of usb '''
def run(self):
''' Runs the actual loop to detect the events '''
self.context = pyudev.Context()
self.monitor = pyudev.Monitor.from_netlink(self.context)
self.monitor.filter_by(subsystem='usb')
self.monitor.start()
for device in iter(self.monitor.poll, None):
if device.action == 'add':
# some action to run on insertion of usb
如果全局变量状态发生变化,我尝试插入一个 break 语句。但它没有用。像这样简单的东西
if TERMINATE == True:
break
我查看了https://pyudev.readthedocs.io/en/latest/api/pyudev.html并通过阅读它看起来像这部分代码
for device in iter(self.monitor.poll, None):
if device.action == 'add':
# some function to run on insertion of usb
是一个无限循环,除非插入超时而不是 None。我想在另一个线程结束时杀死线程。如果我为我的主线程发出退出命令,这个 usbdetector 就会继续运行。关于如何阻止它的任何建议?
(更新)
嘿,
抱歉,我现在采用了一种低技术的方式来解决我的问题。
如果有人知道如何在不需要第二个循环的情况下跳出这个 for 循环,请告诉我
def run(self):
''' Runs the actual loop to detect the events '''
global terminate
self.rmmod_Module()
self.context = pyudev.Context()
self.monitor = pyudev.Monitor.from_netlink(self.context)
self.monitor.filter_by(subsystem='usb')
self.monitor.start()
count = 0
while not terminate:
count = count + 1
print count
for device in iter(partial(self.monitor.poll, 3), None):
if device.action == 'add':
# some function to run on insertion of usb
显然,我将 for 循环嵌套在 while 循环中,等待终止为真。它简单且有效,但是仍然想知道是否有办法在 iter() 循环中退出 for 设备。