def download(self, link, path_to_save=None, output=None, referrer=None, cookie=None, postData=None, user=None, password=None, confirm=False, lflag=None): #print "link =", link #print "referrer =", referrer #print "postData =", postData #print "user ="******"password ="******"path_to_save =", path_to_save #print "output =", output #print "lflag =", lflag if confirm: lflag = 0 else: lflag = 5 try: cc.GetModule(['{ECF21EAB-3AA8-4355-82BE-F777990001DD}', 1, 0]) except: cc.GetModule(self.tlb) import comtypes.gen.IDManLib as idman idman1 = cc.CreateObject(idman.CIDMLinkTransmitter, None, None, idman.ICIDMLinkTransmitter2) if path_to_save: os.path.realpath(path_to_save) idman1.SendLinkToIDM(link, referrer, cookie, postData, user, password, path_to_save, output, lflag)
def __init__(self, username, password): CoInitialize() self._pcm_users_dll = client.GetModule(PCM_USERS_DLL_PATH) self._pcm_dll = client.GetModule(PCM_DLL_PATH) self._pcm_sp_version = get_pcm_10_service_pack(PCM_DLL_PATH) self._username = username self._password = password self._login(self._username, self._password)
def GetText(self, asHTML=True): """ Returns the contents of the the html document as either html or plain text. """ assert False if self.ctrl.Document is None: return "" if not hasattr(sys, 'frozen'): cc.GetModule('mshtml.tlb') from comtypes.gen import MSHTML doc = self.ctrl.Document.QueryInterface(MSHTML.IHTMLDocument2) if not asHTML: # if just fetching the text then get it from the body property return doc.body.innerText # otherwise look in the all property for idx in range(doc.all.length): # the first item with content should be the <html> tag and all its # children. item = doc.all.item(idx) if item is None: continue return item.outerHTML return ""
def connect(self): self.smi = cc.CreateObject('SMIEngine.SMIHost') cc.GetModule('IntegMotorInterface.dll') self.CommInterface = self.smi.QueryInterface( comtypes.gen.INTEGMOTORINTERFACELib.ISMIComm) self.motor_door = None self.establish_link()
def __init__(self, port, *args, **kwargs): self.lib = com.GetModule("Prior.dll") self.port = port self.controller = com.CreateObject(self.lib.Scan()) self.controller.Connect(self.port) self.zobject = com.CreateObject(self.lib.Z())
def ok_click(self): if self.found: shutil.rmtree(self.path) os.mkdir(self.path) try: cc.GetModule(self.dllpath) self.label2.setText('已更新!!') except Exception as e: self.label2.setText(e) pass
def dll_assure(cls): global _DLL_INIT_FLAG if not _DLL_INIT_FLAG: vcredist = VcredistHelper(VCREDIST_VER_REQUIRED, '~/.liqueur') capital_api = CapitalAPIHelper(DLL_VER_REQUIRED, '~/.liqueur') vcredist.auto_install() capital_api.auto_install() cc.GetModule(capital_api.api_path) _DLL_INIT_FLAG = True
def __init__(self): """Create an instance of the task bar.""" if not self._is_windows(): return import comtypes.client as cc cc.GetModule("wintaskbar.tlb") import comtypes.gen.TaskbarLib as tbl self.taskbar = cc.CreateObject( "{56FDF344-FD6D-11d0-958A-006097C9A090}", interface=tbl.ITaskbarList3) self.taskbar.HrInit()
def __init__(self): self.GamryCOM = client.GetModule(setupd["path_to_gamrycom"]) self.devices = client.CreateObject("GamryCOM.GamryDeviceList") # print(devices.EnumSections()) self.pstat = client.CreateObject("GamryCOM.GamryPC6Pstat") # print(devices.EnumSections()) try: self.pstat.Init(self.devices.EnumSections()[0]) # grab first pstat except IndexError: print("No potentiostat is connected! Have you turned it on?") self.temp = []
def __init__(self): threading.Thread.__init__(self) cc.GetModule( os.path.split(os.path.realpath(__file__))[0] + r'\SKCOM.dll') from comtypes.gen import SKCOMLib as sk self.skC = cc.CreateObject(sk.SKCenterLib, interface=sk.ISKCenterLib) self.skQ = cc.CreateObject(sk.SKQuoteLib, interface=sk.ISKQuoteLib) self.EventQ = self.skQ_events(self) self.ConnectionQ = cc.GetEvents(self.skQ, self.EventQ) self.feature_list = [] self.option_list = [] self.feature_code = "" self.option_code = "" self.watchdog = 0
def GetStringSelection(self, asHTML=True): """ Returns the contents of the selected portion of the document as either html or plain text. """ if self.ctrl.Document is None: return "" if not hasattr(sys, 'frozen'): cc.GetModule('mshtml.tlb') from comtypes.gen import MSHTML doc = self.ctrl.Document.QueryInterface(MSHTML.IHTMLDocument2) sel = doc.selection range = sel.createRange() if asHTML: return range.htmlText else: return range.text
def init(): global current if sys.platform.startswith('win'): try: import comtypes.client as cc tbl = cc.GetModule('taskbar.tlb') taskbar = cc.CreateObject('{56FDF344-FD6D-11d0-958A-006097C9A090}', interface=tbl.ITaskbarList3) except: logging.exception( 'Failed to load ITaskbarList3! Disabling Windows integration.') else: logging.info('Activating Windows integration...') current = WindowsIntegration(taskbar) return elif sys.platform.startswith('linux'): try: import gi try: if hasattr(gi, 'require_version'): gi.require_version('Unity', '6.0') except: logging.exception('Failed to specify Unity version.') from gi.repository import Unity except ImportError: # Can't find Unity. pass else: logging.info('Activating Unity integration...') current = UnityIntegration(Unity) return logging.info('Activating generic Linux integration...') current = LinuxIntegration() return logging.warning('No desktop integration active.') current = Integration()
def quiet_load_tlb(tlb_filename): log("quiet_load_tlb(%s)", tlb_filename) #suspend logging during comtypes.client._code_cache and loading of tlb files: #also set minimum to INFO for all of comtypes loggers = [ logging.getLogger(x) for x in ("comtypes.client._code_cache", "comtypes.client._generate") ] saved_levels = [x.getEffectiveLevel() for x in loggers] try: for logger in loggers: logger.setLevel(logging.WARNING) log("loading module from %s", tlb_filename) from comtypes import client #@UnresolvedImport client._generate.__verbose__ = False module = client.GetModule(tlb_filename) log("%s=%s", tlb_filename, module) return module finally: for i, logger in enumerate(loggers): logger.setLevel(saved_levels[i])
def __init__(self,tid,tpw,log): threading.Thread.__init__(self) cc.GetModule(os.path.split(os.path.realpath(__file__))[0] + r'\lib\SKCOM.dll') from comtypes.gen import SKCOMLib as sk self.skC=cc.CreateObject(sk.SKCenterLib,interface=sk.ISKCenterLib) self.skQ=cc.CreateObject(sk.SKQuoteLib,interface=sk.ISKQuoteLib) self.skR=cc.CreateObject(sk.SKReplyLib,interface=sk.ISKReplyLib) #Configuration self.EventQ=self.skQ_events(self) self.ConnectionQ = cc.GetEvents(self.skQ, self.EventQ) self.EventR=self.skR_events(self) self.ConnectionR = cc.GetEvents(self.skR, self.EventR) self.feature_list=[] self.option_list=[] self.stock_list=[] self.feature_code=[] self.option_code=[] self.stock_code=[] self.status=[False,False,False,False] self.watchdog=0 self.id=tid self.pw=tpw self.log=log
def load_side_by_side_dll(dllpath, manifestpath, logger=None): """ Loads COM DLL as inproc server, using side-by-side manifest, returns a generated comtypes module for the DLL or raises Runtime error if fails to activate DLL context properly """ if not logger: logger = logging.getLogger(__name__) ensure_file_exists(dllpath) ensure_file_exists(manifestpath) logger.debug('Loading library "{}"'.format(dllpath)) if not path.exists(dllpath): raise RuntimeError('Library "{}" not found.'.format(dllpath)) generated_module = cc.GetModule(dllpath) if not generated_module: raise RuntimeError('Failed to load library "{}"'.format(dllpath)) logger.debug( 'Library loaded. Initializing activation context with manifest...') activation_result = actontext_internal.activate(manifestpath) if activation_result < 0: raise RuntimeError('Failed to initialize activation context') return generated_module
# # Author: Robin Dunn # # Created: 22-March-2004 # Copyright: (c) 2008-2017 by Total Control Software # Licence: wxWindows license # Tags: phoenix-port #---------------------------------------------------------------------- import wx import wx.lib.activex import comtypes.client as cc import sys if not hasattr(sys, 'frozen'): cc.GetModule( ('{D27CDB6B-AE6D-11CF-96B8-444553540000}', 1, 0) ) from comtypes.gen import ShockwaveFlashObjects clsID = '{D27CDB6E-AE6D-11CF-96B8-444553540000}' progID = 'ShockwaveFlash.ShockwaveFlash.1' class FlashWindow(wx.lib.activex.ActiveXCtrl): def __init__(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name='FlashWindow'): wx.lib.activex.ActiveXCtrl.__init__(self, parent, progID, id, pos, size, style, name) def SetZoomRect(self, left, top, right, bottom):
return found def ole2datetime(oledt): # return set to IST return OLE_TIME_ZERO + datetime.timedelta( days=float(oledt), hours=5, minutes=30) def datetime2ole(dt): return (dt - OLE_TIME_ZERO).total_seconds() / (24 * 60 * 60) # Enter the path of the tlb file module = cc.GetModule( 'C:\Program Files (x86)\TrueData\TrueData Client API x86\Binary COM\TrueData.Velocity.External.tlb' ) class TrueDataExternalEventsSink: def OnBarData(self, RequestId, unknown): global signals global sindex chart = unknown.QueryInterface(module.ITrueDataChart) count = chart.GetCount() lastupdatetime = datetime.datetime.utcnow() symbol = symbol_list[sindex] ohlcarr = []
Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the top-level directory of this distribution and at <https://github.com/Ulm-IQO/qudi/> """ from core.module import Base from interface.spectrometer_interface import SpectrometerInterface import numpy as np import comtypes.client as ctc import win32com.client as w32c from ctypes import byref, pointer, c_long, c_float, c_bool import time import datetime ctc.GetModule(('{1A762221-D8BA-11CF-AFC2-508201C10000}', 3, 11)) import comtypes.gen.WINX32Lib as WinSpecLib class WinSpec32(Base, SpectrometerInterface): """ Hardware module for reading spectra from the WinSpec32 spectrometer software. """ def on_activate(self): """ Activate module. """ w32c.pythoncom.CoInitialize() self.expt_is_running = WinSpecLib.EXP_RUNNING self.path = 'asdf' self.prefix = 'test' self.querytime = 0.001
return _min_adobe_version def get_acroversion(): " Included for backward compatibility" return _min_adobe_version #---------------------------------------------------------------------- if wx.PlatformInfo[1] == 'wxMSW': import wx.lib.activex import comtypes.client as cc import comtypes import ctypes try: # Adobe Reader >= 7.0 cc.GetModule( ('{05BFD3F1-6319-4F30-B752-C7A22889BCC4}', 1, 0) ) progID = 'AcroPDF.PDF.1' _min_adobe_version = 7.0 except: try: # Adobe Reader 5 or 6 cc.GetModule( ('{CA8A9783-280D-11CF-A24D-444553540000}', 1, 0) ) progID = 'PDF.PdfCtrl.5' _min_adobe_version = 5.0 except: pass # Adobe Reader not installed (progID is not defined) # Use get_min_adobe_version() before instantiating PDFWindow #------------------------------------------------------------------------------ class PDFWindow(wx.lib.activex.ActiveXCtrl): def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
from __future__ import absolute_import __copyright__ = "Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License" try: import comtypes.client as cc cc.GetModule('taskbarlib.tlb') import comtypes.gen.TaskbarLib as tbl ITaskbarList3 = cc.CreateObject("{56FDF344-FD6D-11d0-958A-006097C9A090}", interface=tbl.ITaskbarList3) ITaskbarList3.HrInit() #Stops displaying progress and returns the button to its normal state. Call this method with this flag to dismiss the progress bar when the operation is complete or canceled. TBPF_NOPROGRESS = 0x00000000 #The progress indicator does not grow in size, but cycles repeatedly along the length of the taskbar button. This indicates activity without specifying what proportion of the progress is complete. Progress is taking place, but there is no prediction as to how long the operation will take. TBPF_INDETERMINATE = 0x00000001 #The progress indicator grows in size from left to right in proportion to the estimated amount of the operation completed. This is a determinate progress indicator; a prediction is being made as to the duration of the operation. TBPF_NORMAL = 0x00000002 #The progress indicator turns red to show that an error has occurred in one of the windows that is broadcasting progress. This is a determinate state. If the progress indicator is in the indeterminate state, it switches to a red determinate display of a generic percentage not indicative of actual progress. TBPF_ERROR = 0x00000004 #The progress indicator turns yellow to show that progress is currently stopped in one of the windows but can be resumed by the user. No error condition exists and nothing is preventing the progress from continuing. This is a determinate state. If the progress indicator is in the indeterminate state, it switches to a yellow determinate display of a generic percentage not indicative of actual progress. TBPF_PAUSED = 0x00000008 except: #The taskbar API is only available for Windows7, on lower windows versions, linux or Mac it will cause an exception. Ignore the exception and don't use the API ITaskbarList3 = None def setBusy(frame, busy): if ITaskbarList3 is not None: if busy:
import os try: from comtypes import client api = client.GetModule(r"C:\Program Files\Nuance\OPCaptureSDK20\Include\IproPlus.tlb") except: print("Comtypes is not installed on your system or Please update path in OCR-mod-command.py file.") def GetOCRByOmniPage(strInput): obj = client.CreateObject(api.Engine) obj.Init() doc = obj.Documents.Add() doc.Deskew = 4 doc.AutoZoning_Form = True doc.AutoZoning_Column = 2 z = doc.LoadImage(strInput) strOutput = os.path.join(os.getcwd(),"output.txt") z.ConvertToDirectTXT(strOutput,0) strOutputXML = os.path.join(os.getcwd(),"Omnipage_XML_Output.xml") z.ConvertToDirectTXT(strOutputXML,4) strText = "" if os.path.exists(strOutput): with open(strOutput,'r') as f: strText = f.readlines()
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # from .moniker import * from comtypes import * from comtypes import client from ctypes.wintypes import RECT, ULONG from comtypes.automation import IDispatch qedit = client.GetModule("qedit.dll") quartz = client.GetModule("quartz.dll") REFERENCE_TIME = c_longlong LONG_PTR = c_ulong OLE_HANDLE = c_int PIN_IN = 0 PIN_OUT = 1 class BITMAPINFOHEADER(Structure): _fields_ = [('biSize', c_uint32), ('biWidth', c_int), ('biHeight', c_int), ('biPlanes', c_short), ('biBitCount', c_short), ('biCompression', c_uint32), ('biSizeImage', c_uint32), ('biXPelsPerMeter', c_long), ('biYPelsPerMeter', c_long),
def Connect(self): cc.GetModule(POWER_WORLD_EXE) self.saco = cc.CreateObject("pwrworld.SimulatorAuto", dynamic=True) # create SimAuto COM Object
# ActiveX control # # Author: Robin Dunn # # Created: 22-March-2004 # Copyright: (c) 2008-2018 by Total Control Software # Licence: wxWindows license #---------------------------------------------------------------------- import wx import wx.lib.activex import comtypes.client as cc import sys if not hasattr(sys, 'frozen'): cc.GetModule('shdocvw.dll') # IWebBrowser2 and etc. from comtypes.gen import SHDocVw clsID = '{8856F961-340A-11D0-A96B-00C04FD705A2}' progID = 'Shell.Explorer.2' # Flags to be used with the RefreshPage method REFRESH_NORMAL = 0 REFRESH_IFEXPIRED = 1 REFRESH_CONTINUE = 2 REFRESH_COMPLETELY = 3 # Flags to be used with LoadUrl, Navigate, Navigate2 methods NAV_OpenInNewWindow = 0x1 NAV_NoHistory = 0x2 NAV_NoReadFromCache = 0x4
#Set all channel defaults to be A for simplicity because we're only working with 1 channel import comtypes.client as cc from comtypes import COMError import pyvisa as visa cc.GetModule('Ke26XXA.dll') import comtypes.gen.Ke26XXALib as Ke26XXALib from ctypes import byref, pointer, c_long, c_float, c_int32, cast, c_char_p, c_char from matplotlib.pyplot import plot, show from numpy import arange, linspace import time class Ke26XXA(object): name = 'Keithley 26xxA' def __init__(self): self.inst = cc.CreateObject('Ke26XXA.Ke26XXA') def connect(self, visaAddr): self.inst.Initialize(visaAddr, False, False, '') # Sets the voltage for a channel. If cvMode is true sets channel automatically to constant voltage mode def setVoltage(self, v, chan='a', cvMode=True): if cvMode: self.setMode('cv') try: self.inst.Source.Voltage.Level[chan] = v except COMError: raise Ke26XXAException(self.checkError()[1])
""" import wx import wx.msw import ctypes as ct import ctypes.wintypes as wt import comtypes import comtypes.client as cc import comtypes.hresult as hr import sys, os if not hasattr(sys, 'frozen'): f = os.path.join(os.path.dirname(__file__), 'myole4ax.tlb') cc.GetModule(f) from comtypes.gen import myole4ax kernel32 = ct.windll.kernel32 user32 = ct.windll.user32 atl = ct.windll.atl WS_CHILD = 0x40000000 WS_VISIBLE = 0x10000000 WS_CLIPCHILDREN = 0x2000000 WS_CLIPSIBLINGS = 0x4000000 CW_USEDEFAULT = 0x80000000 WM_KEYDOWN = 256 WM_DESTROY = 2 #------------------------------------------------------------------------------
# Capital API in python insert postgresDB-taiwan_finance import psycopg2 import pythoncom, time, os import comtypes.client as cc cc.GetModule(r'D:\api\SKCOM\x64\SKCOM.dll') import comtypes.gen.SKCOMLib as sk # 建立COM物件 skC = cc.CreateObject(sk.SKCenterLib, interface=sk.ISKCenterLib) skQ = cc.CreateObject(sk.SKQuoteLib, interface=sk.ISKQuoterLib) # Some configuration ID = '' PW = '' # 顯示 event 事件, t秒內,每隔一秒,檢查有沒有事件發生 def pumpwait(t=1): for i in range(t): time.sleep(1) pythoncom.PumpWaitingMessages() # 建立事件類別 class skQ_events: def __init__(self): self.KlineData = [] def OnConnection(self, nKind, Code): if Code == 0: if nKind == 3001:
#REF: https://easontseng.blogspot.com/2017/ # -*- coding: utf-8 -*- import time, os, threading, datetime, math import lib._config as conf import comtypes.client as cc print('lib path:', os.path.split(os.path.realpath(__file__))[0] + r'\SKCOM.dll') cc.GetModule(os.path.split(os.path.realpath(__file__))[0] + r'\SKCOM.dll') import comtypes.gen.SKCOMLib as sk SHOW_DETAIL = False class CAP_Thread(threading.Thread): #建立事件類別 class skQ_events: def __init__(self, parent): self.MSG = parent.MSG self.parent = parent def OnConnection(self, nKind, nCode): self.parent.log.critical('[v]OnConnection:', self.MSG(nKind), nKind, self.MSG(nCode)) if nKind == 3003: self.parent.step2() def OnNotifyServerTime(self, sHour, sMinute, sSecond, nTotal): #self.parent.watchdog=0 #關閉以時間做檢查 可能較佳 self.parent.timestr = "{}:{}:{}".format( str(sHour).zfill(2), str(sMinute).zfill(2), str(sSecond).zfill(2))
from comtypes import client client.GetModule("SynCtrl.dll") import comtypes.gen.SYNCTRLLib as synctrl from . import synerror import time class SynDevice: def __init__(self, connection_type=synctrl.SE_ConnectionAny, device_type=synctrl.SE_DeviceAny): self._synapi = client.CreateObject("SynCtrl.SynAPICtrl") if self._synapi.Initialize() == synerror.SYNE_FAIL: raise RuntimeError( "The Synaptics kernel-mode driver is not present on " "the target machine, or the installed driver version " "is less than that necessary to support the Synaptics COM API." ) self._syndev = client.CreateObject("SynCtrl.SynDeviceCtrl") self._synpac = client.CreateObject("SynCtrl.SynPacketCtrl") # TODO: catch COMError lHandle = self._synapi.FindDevice(connection_type, device_type, -1) if lHandle < 0: raise RuntimeError("No appropriate device found.") elif lHandle == synerror.SYNE_FAIL: raise RuntimeError( "The ISynAPICtrl object has not been initialized properly.") if self._syndev.Select(lHandle) == synerror.SYNE_HANDLE: raise ValueError(
""" import sys import comtypes.client as cc import requests import bs4 from bs4 import BeautifulSoup import urlparse import re from os import path proxies = { "http": "http://127.0.0.1:8087", "https": "http://127.0.0.1:8087", } IdmModule = cc.GetModule(['{ECF21EAB-3AA8-4355-82BE-F777990001DD}', 1, 0]) idm = cc.CreateObject('IDMan.CIDMLinkTransmitter', None, None, IdmModule.ICIDMLinkTransmitter2) def show(s): """ For showing stuff in Windows console """ if isinstance(s, unicode): print s.encode('gbk', 'replace') elif isinstance(s, str): print unicode(s, 'utf-8').encode('gbk', 'replace') elif isinstance(s, bs4.element.Tag): show(unicode(s)) else: