Python、comtypes与ArcObjects:创建AppROT对象时出错

1 投票
1 回答
1552 浏览
提问于 2025-04-16 09:44

我正在尝试在 Python 2.6.5 和 ArcGIS 10 SP1 下使用 comtypes 和 ArcObjects。我使用的是纯 Python 方法来包装 ArcObjects 的 OLB 文件,这个方法在这个回答中有介绍,但在 comtypes.CoCreateInstance 方法中遇到了错误。

这是我运行的代码:

def WrapModules():
    #force wrapping of all ArcObjects libraries (OLBs)
    import os
    import comtypes.client
    # change com_dir to whatever it is for you
    com_dir = r'C:\Program Files\ArcGIS\Desktop10.0\com'
    coms = [os.path.join(com_dir, x) for x in os.listdir(com_dir) if os.path.splitext(x)[1].upper() == '.OLB']
    map(comtypes.client.GetModule, coms)

def GetApp():
    """Get a hook into the current session of ArcMap"""
    from comtypes.gen import esriFramework
    pAppROT = NewObj(esriFramework.AppROT, esriFramework.IAppROT)
    if pAppROT is not None:
        iCount = pAppROT.Count
        if iCount == 0:
            print 'No ArcGIS application currently running.  Terminating ...'
            return None
        for i in range(iCount):
            pApp = pAppROT.Item(i)  #returns IApplication on AppRef
            if pApp.Name == 'ArcMap':
                print "ArcMap found"
                return pApp
        print 'No ArcMap session is running at this time.'
    print "No AppROT found"
    return None

def NewObj(MyClass, MyInterface):
    """Creates a new comtypes POINTER object where\n\
    MyClass is the class to be instantiated,\n\
    MyInterface is the interface to be assigned"""
    from comtypes.client import CreateObject
    import traceback
    try:
        ptr = CreateObject(MyClass, interface=MyInterface)
        return ptr
    except:
        print traceback.format_exc()
        return None

if __name__ == "__main__":
    WrapModules()
    pApp = GetApp()
    if pApp is not None:
        print "HWND: %d" % pApp.hWnd
    else:
        print "No ArcGIS application found!"

这是脚本的输出结果:

Traceback (most recent call last):
  File "C:\temp\ComHelpers.py", line 35, in NewObj
    ptr = CreateObject(MyClass, interface=MyInterface)
  File "C:\Python26\ArcGIS10.0\lib\site-packages\comtypes\client\__init__.py", line 235, in CreateObject
    obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
  File "C:\Python26\ArcGIS10.0\lib\site-packages\comtypes\__init__.py", line 1145, in CoCreateInstance
    _ole32.CoCreateInstance(byref(clsid), punkouter, clsctx, byref(iid), byref(p))
  File "_ctypes/callproc.c", line 925, in GetResult
WindowsError: [Error -2147221231] ClassFactory cannot supply requested class

No AppROT found
No ArcGIS application found!

谢谢你们提供的任何见解!

1 个回答

1

为了完整性,这个解决方案是Jason Scheirer在GIS Stack Exchange上发布的:

首先要导入arcpy,你现在没有进行任何许可证检查,也没有设置ArcObjects 10.0的运行环境,所以它找不到CoClass。

撰写回答