使用pyud中的monitor终止usbdector线程

2024-04-26 01:27:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个远程设备上运行着一个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语句。但没用。一些简单的东西,比如

^{pr2}$

我看了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命令,这个usbdector就会继续运行。有什么建议可以阻止它吗?在

(更新)

抱歉,我现在用一种低技术的方法来解决我的问题。在

如果有人知道如何在不需要第二个循环的情况下打破这个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

显然,我在while循环中嵌套了for循环,等待terminate为true。它简单而有效,但是仍然想知道是否有办法在iter()循环中踢出for device。在


Tags: ofthetorunselffordevicecount
1条回答
网友
1楼 · 发布于 2024-04-26 01:27:53

这可能不是你想要的直接答案。与其通过轮询同步监视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设备识别为多个设备。把这些放在一起,你可以做如下的事情。在

^{pr2}$

对于一个usb操作,您可能会得到多个回调,因此可以使用螺纹锁紧()以及访问和编辑时间变量,并且每秒只接受新的回调。我希望这有帮助,很抱歉迟来答复。在

相关问题 更多 >