我有一个在远程设备上运行的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是一个无限循环,除非插入超时而不是不插入。我想在另一个线程结束时杀死这个线程。如果我给我的主线程发quit命令,这个just检测器就会继续运行。对如何阻止它有什么建议吗?
(更新)
嘿,
很抱歉,我用了一种低技术的方法来解决我的问题。
如果有人知道如何在不需要第二个循环的情况下跳出这个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循环中,等待terminate为true。它的简单和有效,但是仍然想知道是否有一种方法可以在iter()循环中踢出for设备。
发布于 2018-09-11 23:46:24
这可能不是你想要的直接答案。与其通过轮询同步监控USB端口,不如使用异步回调,如下面pyudev monitoring device guide异步监控部分所示。
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by('block')
def log_event(action, device):
if 'ID_FS_TYPE' in device:
with open('filesystems.log', 'a+') as stream:
print('{0} - {1}'.format(action, device.get('ID_FS_LABEL')), file=stream)
observer = pyudev.MonitorObserver(monitor, log_event)
observer.start()从代码片段中,您可能会收到单个USB设备操作的多个回调,因为它可能会将单个USB设备识别为多个设备。把这些放在一起,你可以做一些事情,如下所示。
class USBDetector():
''' 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.observer = pyudev.MonitorObserver(self.monitor, self.usbDeviceEventHandler)
self.observer.start()
def usbDeviceEventHandler(self, action, device):
if device.action == 'add':
# some function to run on insertion of usb对于单个usb操作,您可能会获得多个回调,因此您可以使用Thread.lock()实现线程锁定以及访问和编辑时间变量,并且每秒只接受新的回调。我希望这对你有所帮助,很抱歉回复得太晚了。
https://stackoverflow.com/questions/52098616
复制相似问题