如何加载未注册的COM对象?Python受限环境下的解决方案求助
未注册COM DLL的Python加载解决方法
问题说明
我有一个名为ResultScript.dll的动态链接库,已注册时可通过以下代码加载:
import win32com.client bin_reader = win32com.client.Dispatch('ResultScript.BinReader')
但未注册时执行会触发如下错误:
Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> bin_reader = win32com.client.Dispatch('ResultScript.BinReader') File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221164, 'Class not registered', None, None)
因权限限制无法注册该DLL,需寻找替代加载方案。
可行替代方案
方案1:用
win32com直接生成类型库加载
跳过注册步骤,直接从DLL生成类型库并加载实例:import win32com.client dll_path = r"C:\你的DLL路径\ResultScript.dll" # 生成对应类型库 tlb_path = win32com.client.gencache.MakeTypelibForCLSID( 'ResultScript.BinReader', pathname=dll_path ) # 加载类型库模块 module = win32com.client.gencache.EnsureModule( 'ResultScript.BinReader', 0, 1, 0, typelib=tlb_path ) # 创建实例 bin_reader = module.BinReader()方案2:使用
comtypes库加载comtypes支持直接从DLL文件加载COM对象,无需全局注册:import comtypes.client dll_path = r"C:\你的DLL路径\ResultScript.dll" # 直接从DLL创建实例 bin_reader = comtypes.client.CreateObject( 'ResultScript.BinReader', clsctx=comtypes.CLSCTX_INPROC_SERVER, codebase=dll_path )注意:需先安装
comtypes,执行pip install comtypes即可。方案3:用户级注册(无需管理员权限)
若只是没有全局注册权限,可注册到当前用户的注册表分支:regsvr32 /n /i:user ResultScript.dll执行完成后,即可用原
win32com.client.Dispatch代码正常加载。
内容的提问来源于stack exchange,提问作者Mosy
相关产品推荐
相关产品推荐

