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: xlChart.py    From RocketCEA with GNU General Public License v3.0 6 votes vote down vote up
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 #2
Source File: sampler.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #3
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
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 #4
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
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 #5
Source File: gui_button.py    From traffic with MIT License 6 votes vote down vote up
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 #6
Source File: updates.py    From cloudbase-init with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: utils.py    From mobly with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: output_test.py    From mobly with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: testExplorer.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: hfss.py    From pyHFSS with MIT License 5 votes vote down vote up
def __init__(self, app, desktop):
        """
        :type app: HfssApp
        :type desktop: Dispatch
        """
        super(HfssDesktop, self).__init__()
        self.parent = app
        self._desktop = desktop 
Example #11
Source File: grammar_connection.py    From dragonfly with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #12
Source File: testIterators.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: scp.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def __init__(self, ole_object, method_name):
        """
        :param ole_object: The WMI class/instance whose method is to be called
        :param method_name: The name of the method to be called
        """
        try:
            self.ole_object = Dispatch(ole_object)
            self.method = ole_object.Methods_(method_name)
            self.qualifiers = {}
            for q in self.method.Qualifiers_:
                self.qualifiers[q.Name] = q.Value
            self.provenance = "\n".join(self.qualifiers.get("MappingStrings", []))
            
            self.in_parameters = self.method.InParameters
            self.out_parameters = self.method.OutParameters
            if self.in_parameters is None:
                self.in_parameter_names = []
            else:
                self.in_parameter_names = [(i.Name, i.IsArray) for i in self.in_parameters.Properties_]
            if self.out_parameters is None:
                self.out_parameter_names = []
            else:
                self.out_parameter_names = [(i.Name, i.IsArray) for i in self.out_parameters.Properties_]
            
            doc = "%s (%s) => (%s)" % (
                method_name,
                ", ".join([name + ("", "[]")[is_array] for (name, is_array) in self.in_parameter_names]),
                ", ".join([name + ("", "[]")[is_array] for (name, is_array) in self.out_parameter_names])
            )
            privileges = self.qualifiers.get("Privileges", [])
            if privileges:
                doc += " | Needs: " + ", ".join(privileges)
            self.__doc__ = doc
        except pywintypes.com_error:
            handle_com_error() 
Example #15
Source File: Lg_parseANNT.py    From PhyloSuite with GNU General Public License v3.0 5 votes vote down vote up
def save_docx_as(self):
        import pythoncom
        pythoncom.CoInitialize()  # 多线程编程,必须加上这2句才能用win32com模块
        word = wc.Dispatch('Word.Application')
        doc = word.Documents.Open(self.usernota_file)
        sequence = re.sub(r'\[.+?\]|\n| |\t|\r', '', doc.Content.Text).upper()
        self.xml_11 = self.workPath + os.sep + "xml_11.xml"
        doc.SaveAs(self.xml_11, 11)
        doc.Close()
        return sequence 
Example #16
Source File: base_application.py    From pycatia with MIT License 5 votes vote down vote up
def catia_application():
    return Application(Dispatch('CATIA.Application')) 
Example #17
Source File: ABuWinUtil.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def drive_free_space(drive):
    # noinspection PyBroadException
    try:
        fso = com.Dispatch("Scripting.FileSystemObject")
        drv = fso.GetDrive(drive)
        return drv.FreeSpace
    except:
        return 0 
Example #18
Source File: hfss.py    From pyHFSS with MIT License 5 votes vote down vote up
def __init__(self):
        super(HfssApp, self).__init__()
        self._app = Dispatch('AnsoftHfss.HfssScriptInterface') 
Example #19
Source File: recipe-528870.py    From code with MIT License 5 votes vote down vote up
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 
Example #20
Source File: hfss.py    From pyHFSS with MIT License 5 votes vote down vote up
def __init__(self, desktop, project):
        """
        :type desktop: HfssDesktop
        :type project: Dispatch
        """
        super(HfssProject, self).__init__()
        self.parent = desktop
        self._project = project
        self.name = project.GetName() 
Example #21
Source File: hfss.py    From pyHFSS with MIT License 5 votes vote down vote up
def __init__(self, design, setup):
        """
        :type design: HfssDesign
        :type setup: Dispatch
        """
        super(HfssSetup, self).__init__()
        self.parent = design
        self.prop_holder = design._design
        self._setup_module = design._setup_module
        self._reporter = design._reporter
        self._solutions = design._solutions
        self.name = setup
        self.solution_name = setup + " : LastAdaptive"
        self.prop_server = "AnalysisSetup:" + setup
        self.expression_cache_items = [] 
Example #22
Source File: setup_utils.py    From mmvt with GNU General Public License v3.0 5 votes vote down vote up
def create_folder_link(real_fol, link_fol, overwrite=True):
    ret = False
    if not overwrite and is_link(link_fol):
        print('The link {} is already exist'.format(link_fol))
        ret = True
    else:
        if is_windows():
            try:
                if not op.isdir(real_fol):
                    print('The target is not a directory!!')
                    return
                import winshell
                from win32com.client import Dispatch
                path = '{}.lnk'.format(link_fol)
                shell = Dispatch('WScript.Shell')
                shortcut = shell.CreateShortCut(path)
                shortcut.Targetpath = real_fol
                shortcut.save()
                ret = True
            except:
                print("Can't create a link to the folder {}!".format(real_fol))
                ret = False
        else:
            if overwrite and op.islink(link_fol):
                os.remove(link_fol)
            try:
                os.symlink(real_fol, link_fol)
                ret = op.islink(link_fol)
            except:
                print('Problem with creating {} link to {}'.format(link_fol, real_fol))
                ret = False
    return ret 
Example #23
Source File: set_to_startup.py    From Python-Scripts-and-Games with MIT License 5 votes vote down vote up
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 #24
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def Setup(self, plugin):
        """This will be called inside the thread at the beginning."""
        self.plugin = plugin

        class SubEventHandler(EventHandler):
            thread = self
            TriggerEvent = self.plugin.TriggerEvent
        self.EventHandler = SubEventHandler

        self.phoner = None
        self.events = None
        self.phoner = Dispatch("Phoner.CPhoner")
        self.events=DispatchWithEvents(self.phoner, self.EventHandler) 
Example #25
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def initMM(self):
        del self.MM
        del self.events
        self.events = None
        self.MM = Dispatch("SongsDB.SDBApplication")
        self.MM.ShutdownAfterDisconnect = False

        if self.mainThread:
            class SubEventHandler(EventHandler):
                MM = self.MM
                plugin = self.plugin
                TriggerEvent = self.plugin.TriggerEvent
            self.EventHandler = SubEventHandler
            self.events = DispatchWithEvents(self.MM, self.EventHandler) 
Example #26
Source File: add_to_sendTo.py    From Python-Scripts-and-Games with MIT License 5 votes vote down vote up
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 #27
Source File: grammar_connection.py    From dragonfly with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #28
Source File: testExplorer.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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 #29
Source File: errorSemantics.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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 #30
Source File: testAccess.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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.