您的位置:首页 > 移动开发 > Objective-C

使用Python(comtypes)操作ArcGis(ArcObject)的第一步:安装模块到gen文件夹中

2011-03-21 14:22 1216 查看
2011-02-20,星期日

使用Python(comtypes)操作ArcObject的相关对象亦有一段时间了,一直没有系统地总结代码,就现在开始总结一下了。

本文运行的环境:XP sp3+Python2.5+ArcGis(ArcInfo)9.3

注意:ArcGis10中使用python代替了VBA,本文适用如何于在9.x版本上使用python操作ArcObject类库

第一步:安装comtypes

这个模块可以到(http://sourceforge.net/projects/comtypes/files/)载,我使用的版本是:comtypes-0.6.2.win32,关于comtypes的介绍如是说:

comtypes is a lightweight Python COM package, based on the ctypes FFI library, in less than 10000 lines of code (not counting the tests).

comtypes allows to define, call, and implement custom and dispatch-based COM interfaces in pure Python. It works on Windows, 64-bit Windows, and Windows CE.

第二步:导入ArcGis的相关类库文件到comtypes的gen文件夹中

comtypes提供了GetModule方法,将*.olb文件导入到comtypes的gen文件夹中,这样,在python中就可以应用它了,如下面的代码:



根据上面的代码截图,从输出结果可以看到一个新的模块已经生成了,之后可以在python中这样导入它:



就上面的例子,ArcObject中的esriOutput就可以在Python中应用了,那其他模块呢?最简单的方法就是一个一个导入了。

为了方便和全面,我写了一个程序,一次导入所有ArcObject相关模块:

 

view sourceprint?

#-*- coding:cp936 -*-
import
sys,os.path,glob
print
"运行:%s下的/n:   %s"
%
os.path.split(sys.argv[
0
])
 
 
from
comtypes.client
import
GetModule
from
comtypes.client
import
gen_dir as gendir
def
GetArcGisInstallDir():
    
print
'获取ArcGis的安装路径...'
    
import
_winreg
    
keyESRI
=
_winreg.OpenKey(
        
_winreg.HKEY_LOCAL_MACHINE,
"SOFTWARE//ESRI//ArcGIS"
)
    
return
_winreg.QueryValueEx(keyESRI,
"InstallDir"
)[
0
]
#
def
InstallArcObjectsModules():
    
ori_comlibsPath
=
os.path.join(GetArcGisInstallDir(),
'com'
)
    
libNames
=
[os.path.splitext(os.path.basename(v))[
0
]
for
v
                
in
glob.glob(os.path.join(ori_comlibsPath,
'*.olb'
))]
     
 
    
uninstall_libs
=
[v
for
v
in
libNames
if
not
                      
(os.path.isfile(os.path.join(gendir,v
+
'.py'
))
                       
or
os.path.isfile(os.path.join(gendir,v
+
'.pyc'
)))]
     
 
    
if
not
uninstall_libs:
        
print
'所有的ArcObjects模块已安装,你现在可以使用Python操作他们了!'
 
    
for
v
in
uninstall_libs:
        
print
'installing modules:'
+
v
+
'...'
 
        
module_path
=
os.path.join(ori_comlibsPath,v
+
'.olb'
)
        
print
module_path
        
GetModule(module_path)
#
if
__name__
=
=
'__main__'
:
    
InstallArcObjectsModules()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息