Python多线程中试用wmi报错
Python项目中试用wmi模块获得mac地址,
Python 全选
# 获得机器码
def getMID():
global MID
if MID is None:
computeName = os.environ['COMPUTERNAME']
# mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
# MID = computeName + "_" + ("_".join(
# [mac[e:e + 2] for e in range(0, 11, 2)]))
try:
s = wmi.WMI()
for nw in s.Win32_NetworkAdapterConfiguration(): # IPEnabled=0
if MID is None and nw.MACAddress is not None:
MID = computeName + '_' + nw.MACAddress.replace(
':', '_') # 无线局域网适配器 WLAN 物理地址
break
except Exception:
MID = computeName + '-***'
s.co
return MID
单独运行没问题,可如果是在子线程(多进程)中运行,就会报错
wmi -2147221020 无效的语法
错误信息:
Traceback (most recent call last):
File "wmi.py", line 1354, in connect
File "wmi.py", line 258, in handle_com_error
wmi.x_wmi_uninitialised_thread: <x_wmi: Unexpected COM Error (-2147221020, '无效的语法', None, None)>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "run_body.py", line 85, in new_chrome
File "run_body.py", line 52, in refresh_ip
File "libs_api.py", line 33, in get_data
File "libs_api.py", line 23, in getMID
File "wmi.py", line 1357, in connect
wmi.x_wmi_uninitialised_thread: <x_wmi: WMI returned a syntax error: you're probably running inside a thread without first calling pythoncom.CoInitialize[Ex] (no underlying exception)>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "run_body.py", line 131, in run_main
File "run_body.py", line 107, in new_chrome
File "run_body.py", line 107, in new_chrome
File "run_body.py", line 107, in new_chrome
[Previous line repeated 138 more times]
File "run_body.py", line 105, in new_chrome
File "traceback.py", line 167, in format_exc
File "traceback.py", line 121, in format_exception
File "traceback.py", line 497, in __init__
File "traceback.py", line 497, in __init__
File "traceback.py", line 497, in __init__
[Previous line repeated 421 more times]
File "traceback.py", line 473, in __init__
RecursionError: maximum recursion depth exceeded while calling a Python object
解决方案
导入 pythoncom 模块
Python 全选
import pythoncom
初始化 试用wmi模块之前初始化
Python 全选
pythoncom.CoInitialize()
完整代码
Python 全选
# 获得机器码
def getMID():
global MID
if MID is None:
computeName = os.environ['COMPUTERNAME']
# mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
# MID = computeName + "_" + ("_".join(
# [mac[e:e + 2] for e in range(0, 11, 2)]))
try:
pythoncom.CoInitialize()
s = wmi.WMI()
for nw in s.Win32_NetworkAdapterConfiguration(): # IPEnabled=0
if MID is None and nw.MACAddress is not None:
MID = computeName + '_' + nw.MACAddress.replace(
':', '_') # 无线局域网适配器 WLAN 物理地址
break
except Exception:
MID = computeName + '-***'
s.co
return MID
如果还报错,就用
Python 全选
import pythoncom
pythoncom.CoInitialize()
import wmi
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员