def Standalone_OpenGISServer(): GetModule("esriServer.olb") GetModule("esriGeometry.olb") import comtypes.gen.esriServer as esriServer import comtypes.gen.esriGeometry as esriGeometry pServerConn = NewObj(esriServer.GISServerConnection, \ esriServer.IGISServerConnection) pServerConn.Connect("tuswpesri02") pServerManager = pServerConn.ServerObjectManager pServerContext = pServerManager.CreateServerContext("", "") #pUnk = pServerContext.CreateObject("esriGeometry.Polygon") pUnk = pServerContext.CreateObject(CLSID(esriGeometry.Polygon)) pPtColl = CType(pUnk, esriGeometry.IPointCollection) XList = [0, 0, 10, 10] YList = [0, 10, 10, 0] iCount = 4 for i in range(iCount): #pUnk = pServerContext.CreateObject("esriGeometry.Point") pUnk = pServerContext.CreateObject(CLSID(esriGeometry.Point)) pPoint = CType(pUnk, esriGeometry.IPoint) pPoint.PutCoords(XList[i], YList[i]) pPtColl.AddPoint(pPoint) pArea = CType(pPtColl, esriGeometry.IArea) print "Area = ", pArea.Area pServerContext.ReleaseContext()
def start(self): Rhino_tlb = GetModule("C:/Program Files/Rhinoceros 5/System/Rhino5.tlb") RhinoScript_tlb = GetModule("C:/Program Files/Rhinoceros 5/Plug-ins/RhinoScript.tlb") self.Rhino = CreateObject('Rhino5x64.Application').QueryInterface(Rhino_tlb.IRhino5x64Application) while not self.Rhino.IsInitialized(): print('Initialising Rhino...') time.sleep(0.5) print('Rhino initialised!') self.rs = self.Rhino.GetScriptObject().QueryInterface(RhinoScript_tlb.IRhinoScript)
def GetStandaloneModules(): """Import commonly used ArcGIS libraries for standalone scripts""" GetModule("esriSystem.olb") #GetModule("esriGeometry.olb") #GetModule("esriCarto.olb") #GetModule("esriDisplay.olb") GetModule("esriGeoDatabase.olb") GetModule("esriDataSourcesGDB.olb") GetModule("esriDataSourcesFile.olb") GetModule("esriOutput.olb")
def test(self): from comtypes.client import GetModule iem = GetModule("shdocvw.dll") # IDispatch(IUnknown) # IWebBrowser(IDispatch) # IWebBrowserApp(IWebBrowser) # IWebBrowser2(IWebBrowserApp) ## print iem.IWebBrowser2.mro() self.assertTrue(issubclass(iem.IWebBrowser2, iem.IWebBrowserApp)) self.assertTrue(issubclass(iem.IWebBrowserApp, iem.IWebBrowser)) ## print sorted(iem.IWebBrowser.__map_case__.keys()) ## print "=" * 42 ## print sorted(iem.IWebBrowserApp.__map_case__.keys()) ## print "=" * 42 ## print sorted(iem.IWebBrowser2.__map_case__.keys()) ## print "=" * 42 # names in the base class __map_case__ must also appear in the # subclass. for name in iem.IWebBrowser.__map_case__: self.assertTrue(name in iem.IWebBrowserApp.__map_case__, "%s missing" % name) self.assertTrue(name in iem.IWebBrowser2.__map_case__, "%s missing" % name) for name in iem.IWebBrowserApp.__map_case__: self.assertTrue(name in iem.IWebBrowser2.__map_case__, "%s missing" % name)
def InitStandalone(): """Init standalone ArcGIS license""" # Set ArcObjects version import comtypes from comtypes.client import GetModule g = comtypes.GUID("{6FCCEDE0-179D-4D12-B586-58C88D26CA78}") GetModule((g, 1, 0)) import comtypes.gen.ArcGISVersionLib as esriVersion import comtypes.gen.esriSystem as esriSystem pVM = NewObj(esriVersion.VersionManager, esriVersion.IArcGISVersion) # These needs to be the latest version of ArcGIS if not pVM.LoadVersion(esriVersion.esriArcGISDesktop, "10.5.1"): return False # Get license pInit = NewObj(esriSystem.AoInitialize, esriSystem.IAoInitialize) ProductList = [esriSystem.esriLicenseProductCodeArcInfo, \ esriSystem.esriLicenseProductCodeArcEditor, \ esriSystem.esriLicenseProductCodeArcView] for eProduct in ProductList: licenseStatus = pInit.IsProductCodeAvailable(eProduct) if licenseStatus != esriSystem.esriLicenseAvailable: continue licenseStatus = pInit.Initialize(eProduct) return (licenseStatus == esriSystem.esriLicenseCheckedOut) return False
def InitStandalone(): """Init standalone ArcGIS license""" # Set ArcObjects version import comtypes from comtypes.client import GetModule g = comtypes.GUID("{6FCCEDE0-179D-4D12-B586-58C88D26CA78}") GetModule((g, 1, 0)) import comtypes.gen.ArcGISVersionLib as esriVersion import comtypes.gen.esriSystem as esriSystem pVM = NewObj(esriVersion.VersionManager, esriVersion.IArcGISVersion) ### CHANGE PATH!!! if not pVM.LoadVersion( esriVersion.esriArcGISDesktop, "10.4"): # arcpy.GetInstallInfo()['Version']): #"10.7"): return False # Get license pInit = NewObj(esriSystem.AoInitialize, esriSystem.IAoInitialize) ProductList = [esriSystem.esriLicenseProductCodeAdvanced, \ esriSystem.esriLicenseProductCodeStandard, \ esriSystem.esriLicenseProductCodeBasic] for eProduct in ProductList: licenseStatus = pInit.IsProductCodeAvailable(eProduct) if licenseStatus != esriSystem.esriLicenseAvailable: continue licenseStatus = pInit.Initialize(eProduct) return (licenseStatus == esriSystem.esriLicenseCheckedOut) return False
def setInitCOM(self): #Create COM Objects module = GetModule(CapitalDLL) self.skcenter = CreateObject(module.SKCenterLib, interface=module.ISKCenterLib) self.skreply = CreateObject(module.SKReplyLib, interface=module.ISKReplyLib) self.skquote = CreateObject(module.SKQuoteLib, interface=module.ISKQuoteLib) self.module = module #create com signal Object self.skcenterevents = SKCenterLibEventsHandler() self.skreplyevents = SKReplyLibEventsHandler() self.skquoteevents = SKQuoteLibEventsHandler() #regist to COM Object self.centerConn = GetEvents(self.skcenter, self.skcenterevents) self.replyConn = GetEvents(self.skreply, self.skreplyevents) self.quoteConn = GetEvents(self.skquote, self.skquoteevents) #signals - skcenter self.skcenterevents.ontimer.connect(self.timerkeeping_cb) #signals - skquote self.skquoteevents.onnotifyservertime.connect(self.timerkeeping_cb) self.skquoteevents.onnotifystocklist.connect( self.stocklist_cb, QtCore.Qt.QueuedConnection) self.skquoteevents.onconnection.connect(self.onconnection_cb) self.skquoteevents.onnotifyquote.connect(self.onnotifyquote_cb) self.skquoteevents.onnotifyklinedata.connect( self.onnotifyklinedata_cb, QtCore.Qt.QueuedConnection)
def _register_dll_dir(search_paths=None): if search_paths is None: search_paths = [] search_paths = list(search_paths) search_paths.extend(_default_paths) for dll_dir in search_paths: try: GetModule(os.path.join(dll_dir, 'MassSpecDataReader.tlb')) GetModule(os.path.join(dll_dir, 'BaseCommon.tlb')) GetModule(os.path.join(dll_dir, 'BaseDataAccess.tlb')) global DLL_IS_LOADED DLL_IS_LOADED = True return True except Exception: continue else: return False
def _get_client(namespace): import comtypes.client comtypes.client.gen_dir = None comtypes.client._generate.__verbose__ = False from comtypes import CoGetObject from comtypes.client import GetModule wmi_module = GetModule(["{565783C6-CB41-11D1-8B02-00600806D9B6}", 1, 2]) client = CoGetObject(r"winmgmts:{}".format(namespace), interface=wmi_module.ISWbemServicesEx) return client
def __init__(self, fileName): self.msdia = GetModule("msdia140.dll") self.dataSource = CreateObject(self.msdia.DiaSource, interface=self.msdia.IDiaDataSource) ext = fileName.split(os.path.extsep)[-1] if 'pdb' == ext.lower(): self.dataSource.loadDataFromPdb(fileName) else: symPath = os.environ.get('_NT_SYMBOL_PATH', 'SRV**\\\\symbols\\symbols') self.dataSource.loadDataForExe(fileName, symPath, None) self.session = self.dataSource.openSession() self.globalScope = self.session.globalScope
def _register_dll_dir(search_paths=None): from ms_deisotope.config import get_config if search_paths is None: search_paths = [] global DLL_IS_LOADED if DLL_IS_LOADED: return True search_paths = list(search_paths) search_paths.extend(_default_paths) search_paths.extend(get_config().get('vendor_readers', {}).get('agilent-com', [])) for dll_dir in search_paths: try: GetModule(os.path.join(dll_dir, 'MassSpecDataReader.tlb')) GetModule(os.path.join(dll_dir, 'BaseCommon.tlb')) GetModule(os.path.join(dll_dir, 'BaseDataAccess.tlb')) DLL_IS_LOADED = True return True except Exception: continue else: return False
class ArcGisModules: """This class loads the ArcObject librarys as variables""" def __init__(self): pass lib_path = get_arc_object_library_path() module_carto = GetModule("{lib_path}esriCarto.olb".format(lib_path=lib_path)) module_display = GetModule("{lib_path}esriDisplay.olb".format(lib_path=lib_path)) module_gdb = GetModule("{lib_path}esriGeoDatabase.olb".format(lib_path=lib_path)) module_data_source_raster = GetModule("{lib_path}esriDataSourcesRaster.olb".format(lib_path=lib_path)) module_framework = GetModule("{lib_path}esriFramework.olb".format(lib_path=lib_path)) module_map_ui = GetModule("{lib_path}esriArcMapUI.olb".format(lib_path=lib_path)) module_geometry = GetModule("{lib_path}esriGeometry.olb".format(lib_path=lib_path)) module_system = GetModule("{lib_path}esriSystem.olb".format(lib_path=lib_path))
def ArcMap_GetEditWorkspace(): GetDesktopModules() GetModule("esriEditor.olb") import comtypes.gen.esriSystem as esriSystem import comtypes.gen.esriEditor as esriEditor import comtypes.gen.esriGeoDatabase as esriGeoDatabase pApp = GetApp() pID = NewObj(esriSystem.UID, esriSystem.IUID) pID.Value = CLSID(esriEditor.Editor) pExt = pApp.FindExtensionByCLSID(pID) pEditor = CType(pExt, esriEditor.IEditor) if pEditor.EditState == esriEditor.esriStateEditing: pWS = pEditor.EditWorkspace pDS = CType(pWS, esriGeoDatabase.IDataset) print "Workspace name: " + pDS.BrowseName print "Workspace category: " + pDS.Category
class SKThread(QtCore.QObject): module = GetModule(SKCOMDLL) message = QtCore.pyqtSignal(str) def __init__(self, parent=None): super(__class__, self).__init__(parent) @QtCore.pyqtSlot() def process(self): CoInitialize() self._running = True while self._running: time.sleep(0.1) PumpWaitingMessages() def stop(self): self._running = False
def start(self): self.app = CreateObject('Rhino5.Application') self.rsm = GetModule(['{75B1E1B4-8CAA-43C3-975E-373504024FDB}', 1, 0]) print('loading script interface...') attempts = 20 while attempts: try: print('attempt %s' % attempts) self.rsi = self.app.GetScriptObject.QueryInterface( self.rsm.IRhinoScript) break except Exception: time.sleep(0.5) attempts -= 1 if self.rsi is None: raise Exception('error loading script interface...') print('script interface loaded!')
def __init__(self, path=None): GetDesktopModules() self.app = GetCurrentApp() GetModule("esriEditor.olb") self.path = path self.pid = NewObj(esriSystem.UID, esriSystem.IUID) self.pid.Value = CLSID(esriEditor.Editor) self.pext = self.app.FindExtensionByCLSID(self.pid) self.editor = CType(self.pext, esriEditor.IEditor) if self.path is not None: self.wsf = NewObj(esriDataSourcesGDB.FileGDBWorkspaceFactory, esriGeoDatabase.IWorkspaceFactory) self.ws = self.wsf.OpenFromFile(path, 0) self.wse = CType(self.ws, esriGeoDatabase.IWorkspaceEdit) self.ds = CType(self.ws, esriGeoDatabase.IDataset) if self.editor.EditState == esriEditor.esriStateEditing: self.isediting = True else: self.isediting = False
def FindOutgoingInterface(source): """XXX Describe the strategy that is used...""" # If the COM object implements IProvideClassInfo2, it is easy to # find the default autgoing interface. try: pci = source.QueryInterface(comtypes.typeinfo.IProvideClassInfo2) guid = pci.GetGUID(1) except comtypes.COMError: pass else: # another try: block needed? try: interface = comtypes.com_interface_registry[str(guid)] except KeyError: tinfo = pci.GetClassInfo() tlib, index = tinfo.GetContainingTypeLib() from comtypes.client import GetModule GetModule(tlib) interface = comtypes.com_interface_registry[str(guid)] logger.debug("%s using sinkinterface %s", source, interface) return interface # If we can find the CLSID of the COM object, we can look for a # registered outgoing interface (__clsid has been set by # comtypes.client): clsid = source.__dict__.get('__clsid') try: interface = comtypes.com_coclass_registry[clsid]._outgoing_interfaces_[ 0] except KeyError: pass else: logger.debug("%s using sinkinterface from clsid %s", source, interface) return interface ## interface = find_single_connection_interface(source) ## if interface: ## return interface raise TypeError("cannot determine source interface")
import sys from nupic_bridge import nupic_bridge import comtypes import comtypes.server.localserver from comtypes.safearray import safearray_as_ndarray from comtypes.client import GetModule # generate wrapper code for the type library, this needs # to be done only once (but also each time the IDL file changes) GetModule("NupicBridge.tlb") from comtypes.gen.NupicBridgeTypeLib import NupicBridge # Converts a SAFEARRAY to an array that nupic can use def get_array(sa): """Get an array from a safe array type""" with safearray_as_ndarray: return sa[0] # This is the COM server. # It just wraps all the functions of the NupicBridgeClass class, # and does some translations where necessary. class NupicBridgeImpl(NupicBridge): # registry entries _reg_threading_ = "Both" _reg_progid_ = "NupicBridgeTypeLib.NupicBridge.1" _reg_novers_progid_ = "NupicBridgeTypeLib.NupicBridge" _reg_desc_ = "Simple access to Nupic via COM"
if __name__ == '__main__': import os from sys import argv import logging ProgramPath = os.path.dirname(argv[0]) logging.basicConfig(filename=os.path.join(ProgramPath, 'debug.log'), filemode='w', level=logging.DEBUG) from ctypes import POINTER as _POINTER from comtypes import CoCreateInstance, COMObject, CLSCTX_INPROC_SERVER, CLSCTX_ALL from _ctypes import COMError try: from MMDeviceAPILib import MMDeviceEnumerator as _MMDeviceEnumerator, IMMDeviceEnumerator as _IMMDeviceEnumerator, IMMNotificationClient except ImportError: from comtypes.client import GetModule GetModule("mmdeviceapi.tlb") from comtypes.gen.MMDeviceAPILib import MMDeviceEnumerator as _MMDeviceEnumerator, IMMDeviceEnumerator as _IMMDeviceEnumerator, IMMNotificationClient #from comtypes.client import ShowEvents, GetEvents from .MMConstants import * from .EndpointvolumeAPI import * from .PolicyConfigAPI import * _CLSID_MMDeviceEnumerator = _MMDeviceEnumerator._reg_clsid_ def _GetValue(value): """Need to do this in a function as comtypes seems to have a problem if it's in a class.""" return value.__MIDL____MIDL_itf_mmdeviceapi_0003_00850001.pwszVal from functools import partial as _partial
import os from comtypes.client import GetModule, CreateObject from snippets105 import GetStandaloneModules, InitStandalone, GetDesktopModules import snippets105 GetStandaloneModules() InitStandalone() GetDesktopModules() esriCarto = GetModule(r"C:\Program Files (x86)\ArcGIS\Desktop10.5\com\esriCarto.olb") arcMapUI = GetModule(r"C:\Program Files (x86)\ArcGIS\Desktop10.5\com\esriArcMapUI.olb") geoDBUI = GetModule(r"C:\Program Files (x86)\ArcGIS\Desktop10.5\com\esriGeoDatabaseUI.olb") esriSystem = GetModule(r"C:\Program Files (x86)\ArcGIS\Desktop10.5\com\esriSystem.olb") # Layers, in order of importance layer_order = [ 'Address', 'Location', 'Pipe_Nom_Dia', 'Pipe_Material', 'Depth', 'Plan_Number', 'AMIS_ID','Asset_RID', 'Asset_Stage','Install_Date','OBJECTID'] #------------------------------------------------------------------------------- # Setting the current application mx document so you can get access to the table window pApp = snippets105.GetCurrentApp() pDoc = pApp.Document print type(pDoc) pMxDoc = snippets105.CType(pDoc, arcMapUI.IMxDocument) pMap = pMxDoc.FocusMap print type(pMxDoc) print type(pMap) pEnumLayer = pMap.Layers(None,True) pLayer = pEnumLayer.Next() print type(pLayer)
import encodings.cp437 from windows import * from ctypes import * from ctypes.wintypes import * import comtypes from comtypes import IUnknown, GUID, COMMETHOD, CoCreateInstanceEx from comtypes.automation import IDispatch, VARIANT from comtypes.client import wrap, GetModule from comtypes.client.dynamic import Dispatch import comtypes.gen if not hasattr(sys, 'frozen'): GetModule('shdocvw.dll') try: GetModule('msxml2.dll') except: pass try: GetModule('msxml3.dll') except: pass try: GetModule('msxml6.dll') except: pass GetModule('mshtml.tlb') #GetModule('progdlg.tlb')
License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ''' __version__ = "0.0.3" from comtypes.client import GetModule GetModule('oleacc.dll') from comtypes.gen.Accessibility import IAccessible GetModule(r'ia2_api_all.tlb') from comtypes.gen.IAccessible2Lib import IAccessible2 del GetModule import accessible from utils import * from constants import * import registry # Create singleton registry. Registry = registry.Registry() registry.Registry = Registry del registry
import _winreg import math import os import random import sys import traceback import zipfile import ctypes import comtypes import comtypes.server.localserver from Snippets import GetLibPath, NewObj, CType, CLSID, Msg from comtypes.client import GetModule sLibPath = GetLibPath() GetModule(sLibPath + "esriFramework.olb") GetModule(sLibPath + "esriArcMapUI.olb") GetModule("DemoTool.tlb") from comtypes.gen.DemoToolLib import MyTool sCATID_MxCommands = "{B56A7C42-83D4-11D2-A2E9-080009B6F22B}" # CATID_MxCommands (from ArcCATIDs.h) ICONPATH = "C:\\apps\\Demo\\icons\\" QuoteList = ["Oh, intercourse the penguin!", \ "Why did you say Burma?", \ "It's not pining, it's passed on.", \ "THAT'S got Spam in it!", \ "If we took the bones out it wouldn't be crunchy would it?", \ "It's being-hit-on-the-head lessons in here.", \ "In that case, give me a bee license.", \ "It's a bit runny.", \ "I'm afraid what you've got hold of there is an anteater.", \
def GetModule(sModuleName): """ Generate (if not already done) wrappers for COM modules """ from comtypes.client import GetModule sLibPath = GetLibPath() GetModule(os.path.join(sLibPath, sModuleName))
def CreateMXD(path): GetModule('esriCarto.olb') import comtypes.gen.esriCarto as esriCarto pMapDocument = CreateObject(esriCarto.MapDocument, esriCarto.IMapDocument) pMapDocument.New(path)
# Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. # QT4C is licensed under the BSD 3-Clause License, except for the third-party components listed below. # A copy of the BSD 3-Clause License is included in this file. # """用于访问支持IAccessible接口的控件 """ import win32com.client import win32con import win32gui import ctypes import comtypes import six from comtypes.client import GetModule GetModule('oleacc.dll') from comtypes.gen.Accessibility import IAccessible from comtypes.automation import VARIANT class EnumAccessibleObjectRole(object): '''Accessible Object的角色 ''' ROLE_SYSTEM_TITLEBAR = 0x1 ROLE_SYSTEM_MENUBAR = 0x2 ROLE_SYSTEM_SCROLLBAR = 0x3 ROLE_SYSTEM_GRIP = 0x4 ROLE_SYSTEM_SOUND = 0x5 ROLE_SYSTEM_CURSOR = 0x6 ROLE_SYSTEM_CARET = 0x7 ROLE_SYSTEM_ALERT = 0x8
from comtypes.client import CreateObject, GetModule #### Using the IviScope interface #### GetModule('IviScopeTypeLib.dll') from comtypes.gen import IviScopeLib ivi_scope = CreateObject('Tkdpo2k3k4k.Tkdpo2k3k4k', interface=IviScopeLib.IIviScope) ivi_scope.Initialize('USB0::0x0699::0x0411::C012048::INSTR', False, False, '') ivi_scope.Acquisition.ConfigureRecord(TimePerRecord=.1, MinNumPts=1000, AcquisitionStartTime=0) ch1 = ivi_scope.Channels.Item('CH1') ch1.Configure(Range=.1, Offset=0.1, Coupling=IviScopeLib.IviScopeVerticalCouplingDC, ProbeAttenuation=1, Enabled=True) ch1.Offset = 0.05 # Channel parameters can be configured using properties waveform = ivi_scope.Measurements.Item('CH1').ReadWaveform( MaxTimeMilliseconds=100) print "Waveform :", waveform[0] print "Time Origin :", waveform[1] print "Time Step :", waveform[2] #### Using the Tkdpo2k3k4k interface #### from comtypes.gen import Tkdpo2k3k4kLib
def getAoModule(moduleName): GetModule('C:\\Program Files (x86)\\ArcGIS\\Desktop10.1\\com' + moduleName)
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ''' import new import types from comtypes.client import GetModule IAccessible2 = GetModule('ia2.tlb') from comtypes.automation import VARIANT, VT_I4, VT_DISPATCH from ctypes import c_long, oledll, byref, create_unicode_buffer from comtypes.gen.Accessibility import IAccessible from comtypes.gen.IAccessible2Lib import IAccessible2 from comtypes import named_property, COMError, hresult from constants import CHILDID_SELF, \ UNLOCALIZED_ROLE_NAMES, \ UNLOCALIZED_STATE_NAMES def _makeExceptionHandler(func): ''' Builds a function calling the one it wraps in try/except statements catching COMError exceptions.
def initAoModule(): aoLibPath = 'C:\\Program Files (x86)\\ArcGIS\\Desktop10.1\\com\\' GetModule(aoLibPath + 'esriSystem.olb') GetModule(aoLibPath + 'esriGeometry.olb') GetModule(aoLibPath + 'esriGeoDatabase.olb')