错误:x_wmi:意外的COM错误(-2147217406,' OLE错误0x80041002',无,无)
我试图让Windows PC检测到Ardunio的COM端口。代码有时会起作用,有时也不会,当它没有得到上面列出的错误时。
通过插入和删除Ardunio来测试代码(为Windows提供足够的时间来识别它被删除)。我试着搜索错误但没有出现。
编辑: 通过更多搜索,我发现它与Object Not Found Error有关。当任何COM端口发生变化时(当我插入任何USB设备时)会发生这种情况。代码可以处理中途改变的列表,因此会抛出此错误。我不知道如何以这种方式处理错误,它允许USB设备改变。
langpy:
import os
import time
import ctypes
import wmi
import thread
import pythoncom
import locale
def lang():
localelang = locale.getdefaultlocale()
language = str(localelang)[2:7]
#print (language)
return language
def port():
while True:
pythoncom.CoInitialize()
Ardport = ""
c = wmi.WMI()
wql = "Select * From Win32_USBControllerDevice"
for item in c.query(wql):
s = str(item.Dependent.Caption)
#print (item.Dependent.Caption)
strfind = "Arduino"
strignore = "bootloader"
if (s.find(strfind) >= 0 and s.find(strignore) == -1):
Ardport = item.Dependent.Caption
time.sleep(1)
return Ardport
主要代码:
# -*- coding: utf-8 -*-
import time
import thread
import os
import serial
import sys
import ctypes
import wmi
from langpy import lang
from langpy import port
import pythoncom
class service_test:
def __init__(self):
thread.start_new(self.check_for_Ardunio, tuple())
def check_for_Ardunio(self):
comp = ""
reply = ""
j1 = -1
while True:
plang = (str(lang()))
pport = (str(port()))
if (pport != ""):
j1 = pport[-2:-1]
comp = ('COM' + j1)
if (reply == "reply" and j1 < 0):
ser = serial.Serial(comp, 9600, timeout=1)
if(ser.isOpen()):
ser.write(lang)
print ("sent message")
else:
time.sleep(1)
reply = ""
j1 = -1
comp = 'COM'
#DEBUGGING
print(comp)
print(plang)
print(pport)
print (j1)
print (str(reply))
print ("")
if __name__ == "__main__":
tst = service_test()
完整错误报告:
Unhandled exception in thread started by <bound method service_test.check_for_Ardunio of <__main__.service_test instance at 0x01FEE6C0>>
Traceback (most recent call last):
File "C:\Users\LeakDetectSys\Desktop\Keyboard\testing\application\test1wc.py", line 27, in check_for_Ardunio
pport = (str(port()))
File "C:\Users\LeakDetectSys\Desktop\Keyboard\testing\application\langpy.py", line 25, in port
s = str(item.Dependent.Caption)
File "C:\Python27\lib\site-packages\wmi.py", line 555, in __getattr__
return WMI (moniker=value)
File "C:\Python27\lib\site-packages\wmi.py", line 1290, in connect
handle_com_error ()
File "C:\Python27\lib\site-packages\wmi.py", line 241, in handle_com_error
raise klass (com_error=err)
wmi.x_wmi: <x_wmi: Unexpected COM Error (-2147217406, 'OLE error 0x80041002', None, None)>