|-转 解决无法加载UIAutomationCore.dll的报错
上述错误是在打包后的软件中出现,在PyCharm的运行过程中并没有出现。
解决办法,再项目源码里引入
from comtypes.gen.UIAutomationClient import IUIAutomation
前言: 此问题是在Python开发环境下关于UIAutomation的报错问题,问题来源于生产环境中的几台WIN10系统报错。
module 'comtypes.gen.UIAutomationClient' has no attribute 'IUIAutomation'Can not load UIAutomationCore.dll.1, You may need to install Windows Update KB971513 if your OS is Windows XP, see https://github.com/yinkaisheng/WindowsUpdateKB9715...2, you need to use an UIAutomationInitializerInThread object if use uiautomation in a thread, see demos/uiautomation_in_thread.py
因为在生产环境中出现,当时是怀疑是UIAutomationCore.dll在系统中没有生效,所以尝试过如下的方法(以管理员身份执行如下cmd命令),但始终没有效果,该报错还是报错;也怀疑过WIN10上缺少KB971513的补丁,为此还特地找过对应的补丁安装,但是该补丁只适用于Windows XP系统,在安装的时候存在类似“当前系统无法安装”的提示。
>cd C:\Windows\System32 >regsvr32 UIAutomationCore.dll
由于生产环境不联外网,不好远程调试。本地开发环境又复现不出该问题,
所以当时,虽然无奈地将原因归结于未知的系统原因,但只能先弃用有报错的几台WIN10系统,换别的系统进行业务操作。
直到现在,这个问题过去了有将近半年的时间,终于在开发环境上复现了!
初步定位,是在执行control = uiautomation.ControlFromPoint()的语句时出错,于是在此处捕获异常后打印堆栈信息如下:
Traceback (most recent call last):
File "test_hook.py", line 112, in get_mouse
File "uiautomation\uiautomation.py", line 8164, in ControlFromPoint
File "uiautomation\uiautomation.py", line 52, in instance
File "uiautomation\uiautomation.py", line 71, in __init__
File "uiautomation\uiautomation.py", line 60, in __init__
AttributeError: module 'comtypes.gen.UIAutomationClient' has no attribute 'IUIAutomation'
然后根据堆栈信息找到出错位置对应的uiautomation.py源码
class _AutomationClient:
_instance = None
@classmethod
def instance(cls) -> '_AutomationClient':
"""Singleton instance (this prevents com creation on import)."""
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
tryCount = 3
for retry in range(tryCount):
try:
self.UIAutomationCore = comtypes.client.GetModule("UIAutomationCore.dll")
self.IUIAutomation = comtypes.client.CreateObject("{ff48dba4-60ef-4201-aa87-54103eef594e}", interface=self.UIAutomationCore.IUIAutomation)
self.ViewWalker = self.IUIAutomation.RawViewWalker
#self.ViewWalker = self.IUIAutomation.ControlViewWalker
break
except Exception as ex:
if retry + 1 == tryCount:
Logger.WriteLine('''
{}
Can not load UIAutomationCore.dll.
1, You may need to install Windows Update KB971513 if your OS is Windows XP, see https://github.com/yinkaisheng/WindowsUpdateKB9715......