python wmi watch\u for inside a thread导致异常

2024-09-30 18:25:48 发布

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

我有以下代码:

import subprocess
import threading
import wmi

class DriveWatcher:

    @property
    def drive_watcher_stop_event(self):
        return self._drive_watcher_stop_event
    @drive_watcher_stop_event.setter
    def drive_watcher_stop_event(self, drive_watcher_stop_event):
        self._drive_watcher_stop_event = drive_watcher_stop_event

    @property
    def drive_watcher_thread(self):
        return self._drive_watcher_thread
    @drive_watcher_thread.setter
    def drive_watcher_thread(self, drive_watcher_thread):
        self._drive_watcher_thread = drive_watcher_thread

    def __init__(self):
        self.c = wmi.WMI()
        self.watcher = self.c.Win32_DiskDrive.watch_for()  # InterfaceType="USB"
        self.drive_watcher_stop_event = threading.Event()
        self.drive_watcher_thread = None

    def drive_watcher_loop(self):
        while not self.drive_watcher_stop_event.is_set():
            try:
                disk = self.watcher(timeout_ms=10000)
                print(disk)
            except wmi.x_wmi_timed_out:
                pass


    def start_drive_watcher(self):
        if self.drive_watcher_thread:
            if self.drive_watcher_stop_event.is_set():
                self.drive_watcher_stop_event.clear()
        else:
            self.drive_watcher_thread = threading.Thread(target=self.drive_watcher_loop, args=())
            self.drive_watcher_thread.daemon = True
            self.drive_watcher_thread.start()

    def stop_drive_watcher(self):
        self.drive_watcher_stop_event.set()

watcher = media_tools.DriveWatcher()
watcher.start_drive_watcher()

它会导致以下异常:

event = self.wmi_event.NextEvent (timeout_ms) File ">", line 2, in NextEvent pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'SWbemEventSource', None, None, 0, -2147221008), None)

是什么原因造成的?如何排除这些不明显的异常?你知道吗


Tags: importselfnoneeventdefpropertydrivewmi