python - 线程内的wmi watch_for会导致异常

问题描述 投票:0回答:1

我有以下代码:

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)文件“>”,第2行,在NextEvent中pywintypes.com_error:( - 21470356767,'异常发生。',(0,'SWbemEventSource',无,无,0,-2147221008) , 没有)

是什么造成的?如何解决此类非明显异常?

python multithreading exception wmi
1个回答
1
投票

不一定是你的代码。我遇到了类似的问题。请参阅https://www.thepythoncorner.com/2018/08/how-to-create-a-windows-service-in-python/ - '如果出现问题...'部分短版本:检查pythoncom36.dll和pywintypes36.dll是否在win32目录中(pythonservice.exe所在的位置)

© www.soinside.com 2019 - 2024. All rights reserved.