Python win32com.client.Dispatch() Examples
The following are 30
code examples of win32com.client.Dispatch().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
win32com.client
, or try the search function
.

Example #1
Source File: testExplorer.py From ironpython2 with Apache License 2.0 | 6 votes |
def TestObjectFromWindow(): # Check we can use ObjectFromLresult to get the COM object from the # HWND - see KB Q249232 # Locating the HWND is different than the KB says... hwnd = win32gui.FindWindow('IEFrame', None) for child_class in ['TabWindowClass', 'Shell DocObject View', 'Internet Explorer_Server']: hwnd = win32gui.FindWindowEx(hwnd, 0, child_class, None) assert hwnd, "Couldn't find '%s'" % (child_class,) # But here is the point - once you have an 'Internet Explorer_Server', # you can send a message and use ObjectFromLresult to get it back. msg = win32gui.RegisterWindowMessage("WM_HTML_GETOBJECT") rc, result = win32gui.SendMessageTimeout(hwnd, msg, 0, 0, win32con.SMTO_ABORTIFHUNG, 1000) ob = pythoncom.ObjectFromLresult(result, pythoncom.IID_IDispatch, 0) doc = Dispatch(ob) # just to prove it works, set the background color of the document. for color in "red green blue orange white".split(): doc.bgColor = color time.sleep(0.2)
Example #2
Source File: output_test.py From mobly with Apache License 2.0 | 6 votes |
def test_shortcut(self): """Verifies the shortcut is created and links properly.""" shortcut_path = os.path.join(self.log_dir, self.testbed_name, 'latest.lnk') shell = client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(shortcut_path) self.assertFalse(shortcut.Targetpath) mock_test_config = self.create_mock_test_config( self.base_mock_test_config) tr = test_runner.TestRunner(self.log_dir, self.testbed_name) with tr.mobly_logger(): pass shortcut = shell.CreateShortCut(shortcut_path) # Normalize paths for case and truncation normalized_shortcut_path = os.path.normcase( win32file.GetLongPathName(shortcut.Targetpath)) normalized_logger_path = os.path.normcase( win32file.GetLongPathName(logging.log_path)) self.assertEqual(normalized_shortcut_path, normalized_logger_path)
Example #3
Source File: utils.py From mobly with Apache License 2.0 | 6 votes |
def create_alias(target_path, alias_path): """Creates an alias at 'alias_path' pointing to the file 'target_path'. On Unix, this is implemented via symlink. On Windows, this is done by creating a Windows shortcut file. Args: target_path: Destination path that the alias should point to. alias_path: Path at which to create the new alias. """ if platform.system() == 'Windows' and not alias_path.endswith('.lnk'): alias_path += '.lnk' if os.path.lexists(alias_path): os.remove(alias_path) if platform.system() == 'Windows': from win32com import client shell = client.Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(alias_path) shortcut.Targetpath = target_path shortcut.save() else: os.symlink(target_path, alias_path)
Example #4
Source File: updates.py From cloudbase-init with Apache License 2.0 | 6 votes |
def set_automatic_updates(enabled): # TODO(alexpilotti): the following settings are ignored on # Windows 10 / Windows Server 2016 build 14393 auto_update = client.Dispatch("Microsoft.Update.AutoUpdate") if enabled: auto_update.Settings.NotificationLevel = AU_SCHEDULED_INSTALLATION osutils = osutils_factory.get_os_utils() if not osutils.check_os_version(6, 2): # NOTE(alexpilotti): this setting is not supported starting # with Windows 8 / Windows Server 2012 hour = random.randint(MIN_INSTALL_HOUR, MAX_INSTALL_HOUR) auto_update.SettingsScheduledInstallationTime = hour else: auto_update.Settings.NotificationLevel = AU_DISABLED auto_update.Settings.Save()
Example #5
Source File: xlChart.py From RocketCEA with GNU General Public License v3.0 | 6 votes |
def __init__(self,xlsFile="", Visible=1): self.xlApp = Dispatch("Excel.Application") self.xlApp.Visible = Visible xlChart.numWkBooks = xlChart.numWkBooks + 1 # I don't think the sheet and column lists should be mapped # (unfortunately, they are right now) self.sheetList = [] self.chartList = [] self.chartNColumns = [] self.chartNRows = [] self.leaveOpen = 1 self.nRows = 0 self.nColumns = 0 self.formula = xlChFormula.xlChFormula() # a scratch variable if len(xlsFile)>0: # opening an existing XLS file xlsFile = os.path.abspath(xlsFile) # Excel likes absolute path names self.xlApp.Workbooks.Open(xlsFile) self.initFromXLSFile() self.xlBook = None else: # making a new XLS file self.xlBook = self.xlApp.Workbooks.Add() self.xlSheet = self.xlApp.Sheets(1) self.sheetList.append( self.xlSheet )
Example #6
Source File: gui_button.py From traffic with MIT License | 6 votes |
def make_app(self): with open("traffic.bat", "w") as fh: fh.write(self.windows_batch.format(sys.executable)) try: from win32com.client import Dispatch except ImportError: subprocess.call("conda install pywin32") print("Missing package installed, relaunch script") return path = "traffic.lnk" target = str(Path("traffic.bat").absolute()) icon_path = ICON_PATH / "travel.ico" shell = Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(path) shortcut.TargetPath = target shortcut.IconLocation = icon_path.as_posix() shortcut.save()
Example #7
Source File: __init__.py From EventGhost with GNU General Public License v2.0 | 6 votes |
def __start__(self): try: self.comObj = GetActiveObject(YARD_CLSID) except com_error: self.StartYardServer() try: self.comObj = GetActiveObject(YARD_CLSID) except: raise if self.comObj: self.comObj = Dispatch(YARD_CLSID) class SubEventHandler(EventHandler): plugin = self TriggerEvent = self.TriggerEvent self.workerThread = YardWorkerThread(self, SubEventHandler) try: self.workerThread.Start( 60.0 ) except: self.workerThread = None raise self.Exception( self.text.errorMesg ) self.isEnabled = True
Example #8
Source File: __init__.py From EventGhost with GNU General Public License v2.0 | 6 votes |
def __start__(self, hostname, username, password): self.hsi = Dispatch("HomeSeer2.application") self.connected = False self.hostname = hostname self.username = username self.password = password print "Trying to connect to Homeseer-host " + self.hostname + " using user " + self.username + "." self.hsi.SetHost(self.hostname) rval = self.hsi.Connect(self.username, self.password) if rval == "": print "Successfully connected to Homeseer " + self.hostname + " using user " + self.username + "." self.connected = True else: print "Error: " + rval self.hsi.Disconnect self.connected = False if self.connected: self.hs = Dispatch("homeseer.application")
Example #9
Source File: sampler.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_connection(self): """ Create a new WMI connection """ self.logger.debug( u"Connecting to WMI server (host=%s, namespace=%s, provider=%s, username=%s).", self.host, self.namespace, self.provider, self.username, ) additional_args = [] if self.provider != ProviderArchitecture.DEFAULT: context = Dispatch("WbemScripting.SWbemNamedValueSet") context.Add("__ProviderArchitecture", self.provider) additional_args = [None, "", 128, context] locator = Dispatch("WbemScripting.SWbemLocator") connection = locator.ConnectServer(self.host, self.namespace, self.username, self.password, *additional_args) return connection
Example #10
Source File: AddToTaskbar.py From Python-Scripts-and-Games with MIT License | 5 votes |
def addToTaskbar(file_path, dir_path, name): you = os.getlogin() startup = os.path.join('C:\\Users', you, 'AppData', 'Roaming', 'Microsoft', 'Internet Explorer', 'Quick Launch', 'User Pinned', 'TaskBar') name = name + '.lnk' path = os.path.join(startup, name) shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(path) shortcut.Targetpath = file_path shortcut.WorkingDirectory = dir_path shortcut.IconLocation = file_path shortcut.save()
Example #11
Source File: add_to_sendTo.py From Python-Scripts-and-Games with MIT License | 5 votes |
def make_shortcut(file_path, dir_path, name): you = os.getlogin() startup = os.path.join('C:\\Users', you, 'AppData', 'Roaming', 'Microsoft', 'Windows', 'SendTo') name = name + '.lnk' path = os.path.join(startup, name) shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(path) shortcut.Targetpath = file_path shortcut.WorkingDirectory = dir_path shortcut.IconLocation = file_path shortcut.save()
Example #12
Source File: set_to_startup.py From Python-Scripts-and-Games with MIT License | 5 votes |
def make_shortcut(file_path, dir_path, name): you = os.getlogin() startup = os.path.join('C:\\Users', you, 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup') name = name + '.lnk' path = os.path.join(startup, name) shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(path) shortcut.Targetpath = file_path shortcut.WorkingDirectory = dir_path shortcut.IconLocation = file_path shortcut.save()
Example #13
Source File: scp.py From ironpython2 with Apache License 2.0 | 5 votes |
def ScpCreate( service_binding_info, service_class_name, # Service class string to store in SCP. account_name = None, # Logon account that needs access to SCP. container_name = None, keywords = None, object_class = "serviceConnectionPoint", dns_name_type = "A", dn = None, dns_name = None, ): container_name = container_name or service_class_name if not dns_name: # Get the DNS name of the local computer dns_name = win32api.GetComputerNameEx(win32con.ComputerNameDnsFullyQualified) # Get the distinguished name of the computer object for the local computer if dn is None: dn = win32api.GetComputerObjectName(win32con.NameFullyQualifiedDN) # Compose the ADSpath and bind to the computer object for the local computer comp = adsi.ADsGetObject("LDAP://" + dn, adsi.IID_IDirectoryObject) # Publish the SCP as a child of the computer object keywords = keywords or [] # Fill in the attribute values to be stored in the SCP. attrs = [ ("cn", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (container_name,)), ("objectClass", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (object_class,)), ("keywords", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, keywords), ("serviceDnsName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (dns_name,)), ("serviceDnsNameType", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (dns_name_type,)), ("serviceClassName", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (service_class_name,)), ("serviceBindingInformation", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, (service_binding_info,)), ] new = comp.CreateDSObject("cn=" + container_name, attrs) logger.info("New connection point is at %s", container_name) # Wrap in a usable IDispatch object. new = Dispatch(new) # And allow access to the SCP for the specified account name AllowAccessToScpProperties(account_name, new) return new
Example #14
Source File: scriptdispatch.py From ironpython2 with Apache License 2.0 | 5 votes |
def _dynamic_(self, name, lcid, wFlags, args): # Ensure any newly added items are available. self.engine.RegisterNewNamedItems() self.engine.ProcessNewNamedItemsConnections() if wFlags & pythoncom.INVOKE_FUNC: # attempt to call a function try: func = getattr(self.scriptNamespace, name) if not _is_callable(func): raise AttributeError(name) # Not a function. realArgs = [] for arg in args: if type(arg)==PyIDispatchType: realArgs.append(Dispatch(arg)) else: realArgs.append(arg) try: # xxx - todo - work out what code block to pass??? return self.engine.ApplyInScriptedSection(None, func, tuple(realArgs)) except COMException, (hr, msg, exc, arg): raise except AttributeError: if not wFlags & pythoncom.DISPATCH_PROPERTYGET: raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) if wFlags & pythoncom.DISPATCH_PROPERTYGET: # attempt to get a property try: ret = getattr(self.scriptNamespace, name) if _is_callable(ret): raise AttributeError(name) # Not a property. except AttributeError: raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) except COMException, instance: raise except:
Example #15
Source File: testIterators.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_nonenum_wrapper(self): # Check our raw PyIDispatch ob = self.object._oleobj_ try: for i in ob: pass self.fail("Could iterate over a non-iterable object") except TypeError: pass # this is expected. self.assertRaises(TypeError, iter, ob) self.assertRaises(AttributeError, getattr, ob, "next") # And our Dispatch wrapper ob = self.object try: for i in ob: pass self.fail("Could iterate over a non-iterable object") except TypeError: pass # this is expected. # Note that as our object may be dynamic, we *do* have a __getitem__ # method, meaning we *can* call iter() on the object. In this case # actual iteration is what fails. # So either the 'iter(); will raise a type error, or an attempt to # fetch it try: iter(ob).next() self.fail("Expected a TypeError fetching this iterator") except TypeError: pass # And it should never have a 'next' method self.assertRaises(AttributeError, getattr, ob, "next")
Example #16
Source File: testIterators.py From ironpython2 with Apache License 2.0 | 5 votes |
def setUp(self): def factory(): ob = self.object.GetCollection() flags = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET enum = ob._oleobj_.Invoke(pythoncom.DISPID_NEWENUM, 0, flags, 1) return ob, enum.QueryInterface(pythoncom.IID_IEnumVARIANT) self.expected_data = [1,'Two',3] sv = win32com.server.util.wrap(SomeObject(self.expected_data)) self.object = Dispatch(sv) self.iter_factory = factory
Example #17
Source File: testExplorer.py From ironpython2 with Apache License 2.0 | 5 votes |
def TestAll(): try: try: iexplore = win32com.client.dynamic.Dispatch("InternetExplorer.Application") TestExplorer(iexplore) win32api.Sleep(1000) iexplore = None # Test IE events. TestExplorerEvents() # Give IE a chance to shutdown, else it can get upset on fast machines. time.sleep(2) # Note that the TextExplorerEvents will force makepy - hence # this gencache is really no longer needed. from win32com.client import gencache gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1) iexplore = win32com.client.Dispatch("InternetExplorer.Application") TestExplorer(iexplore) except pythoncom.com_error, exc: if exc.hresult!=winerror.RPC_E_DISCONNECTED: # user closed the app! raise finally: iexplore = None
Example #18
Source File: errorSemantics.py From ironpython2 with Apache License 2.0 | 5 votes |
def testLogger(): assert not hasattr(win32com, "logger") handler = TestLogHandler() formatter = logging.Formatter('%(message)s') handler.setFormatter(formatter) log = logging.getLogger("win32com_test") log.addHandler(handler) win32com.logger = log # Now throw some exceptions! # Native interfaces com_server = wrap(TestServer(), pythoncom.IID_IStream) try: com_server.Commit(0) raise RuntimeError("should have failed") except pythoncom.error: pass assert handler.num_emits == 1, handler.num_emits handler.num_emits = 0 # reset com_server = Dispatch(wrap(TestServer())) try: com_server.Commit(0) raise RuntimeError("should have failed") except pythoncom.error: pass assert handler.num_emits == 1, handler.num_emits
Example #19
Source File: testAccess.py From ironpython2 with Apache License 2.0 | 5 votes |
def DoDumpAccessInfo(dbname): import daodump a = forms = None try: sys.stderr.write("Creating Access Application...\n") a=Dispatch("Access.Application") print "Opening database %s" % dbname a.OpenCurrentDatabase(dbname) db = a.CurrentDb() daodump.DumpDB(db,1) forms = a.Forms print "There are %d forms open." % (len(forms)) # Uncommenting these lines means Access remains open. # for form in forms: # print " %s" % form.Name reports = a.Reports print "There are %d reports open" % (len(reports)) finally: if not a is None: sys.stderr.write("Closing database\n") try: a.CloseCurrentDatabase() except pythoncom.com_error: pass # Generate all the support we can.
Example #20
Source File: testPippo.py From ironpython2 with Apache License 2.0 | 5 votes |
def setUp(self): from win32com.test.util import RegisterPythonServer from win32com.test import pippo_server RegisterPythonServer(pippo_server.__file__, "Python.Test.Pippo") # create it. self.object = Dispatch("Python.Test.Pippo")
Example #21
Source File: engine.py From dragonfly with GNU Lesser General Public License v3.0 | 5 votes |
def connect(self): """ Connect to back-end SR engine. """ self._recognizer = Dispatch(self.recognizer_dispatch_name) self._speaker = Dispatch("SAPI.SpVoice") self._compiler = Sapi5Compiler()
Example #22
Source File: engine.py From dragonfly with GNU Lesser General Public License v3.0 | 5 votes |
def recognition_failure_callback(self, StreamNumber, StreamPosition, Result): func = getattr(self.grammar, "process_recognition_failure", None) self._process_grammar_callback(func, results=Dispatch(Result))
Example #23
Source File: grammar_connection.py From dragonfly with GNU Lesser General Public License v3.0 | 5 votes |
def connect(self): if not self._app_name: return True try: self._application = Dispatch(self._app_name) except com_error as e: if self._log_begin: self._log_begin.warning("Grammar %s: failed to connect to " "%r: %s.", self, self._app_name, e) return False else: [r.activate() for r in self._rules if not r.active] return True
Example #24
Source File: winrmconfig.py From cloudbase-init with Apache License 2.0 | 5 votes |
def _get_wsman_session(self): wsman = client.Dispatch('WSMan.Automation') return wsman.CreateSession()
Example #25
Source File: windows.py From cloudbase-init with Apache License 2.0 | 5 votes |
def firewall_create_rule(self, name, port, protocol, allow=True): if not allow: raise NotImplementedError() fw_port = client.Dispatch("HNetCfg.FWOpenPort") fw_port.Name = name fw_port.Protocol = self._get_fw_protocol(protocol) fw_port.Port = port fw_port.Scope = self._FW_SCOPE_ALL fw_port.Enabled = True fw_mgr = client.Dispatch("HNetCfg.FwMgr") fw_profile = fw_mgr.LocalPolicy.CurrentProfile fw_profile = fw_profile.GloballyOpenPorts.Add(fw_port)
Example #26
Source File: windows.py From cloudbase-init with Apache License 2.0 | 5 votes |
def firewall_remove_rule(self, name, port, protocol, allow=True): if not allow: raise NotImplementedError() fw_mgr = client.Dispatch("HNetCfg.FwMgr") fw_profile = fw_mgr.LocalPolicy.CurrentProfile fw_protocol = self._get_fw_protocol(protocol) fw_profile = fw_profile.GloballyOpenPorts.Remove(port, fw_protocol)
Example #27
Source File: dsofile.py From cross3d with MIT License | 5 votes |
def __init__(self): super(DSOFile, self).__init__() self.dso = _Dispatch('DSOFile.OleDocumentProperties')
Example #28
Source File: engine.py From dragonfly with GNU Lesser General Public License v3.0 | 5 votes |
def connect(self): """ Connect to back-end SR engine. """ self._recognizer = Dispatch(self._recognizer_dispatch_name) self._speaker = Dispatch("SAPI.SpVoice") self._compiler = Sapi5Compiler()
Example #29
Source File: grammar_connection.py From dragonfly with GNU Lesser General Public License v3.0 | 5 votes |
def connect(self): if not self._app_name: return True try: self._application = Dispatch(self._app_name) except com_error, e: if self._log_begin: self._log_begin.warning("Grammar %s: failed to" " connect to %r: %s." % (self, self._app_name, e)) return False
Example #30
Source File: recipe-528870.py From code with MIT License | 5 votes |
def __init__(self, file_name, default_sheet_name, make_visible=False): """Open spreadsheet""" self.excelapp = Dispatch("Excel.Application") if make_visible: self.excelapp.Visible = 1 #fun to watch! self.excelapp.Workbooks.Add() self.workbook = self.excelapp.ActiveWorkbook self.file_name = file_name self.default_sheet = self.excelapp.ActiveSheet self.default_sheet.Name = default_sheet_name