Python pythoncom.CoInitialize() Examples

The following are 30 code examples of pythoncom.CoInitialize(). 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 pythoncom , or try the search function .
Example #1
Source File: adodbapi.py    From ironpython2 with Apache License 2.0 8 votes vote down vote up
def connect(connstr, timeout=30):               #v2.1 Simons
    "Connection string as in the ADO documentation, SQL timeout in seconds"
    try:
        if not onIronPython:
            pythoncom.CoInitialize()             #v2.1 Paj
        conn=Dispatch('ADODB.Connection') #connect _after_ CoIninialize v2.1.1 adamvan
    except:
        raise InterfaceError #Probably COM Error
    try:
        conn.CommandTimeout=timeout             #v2.1 Simons
        conn.ConnectionString=connstr
    except:
        raise Error
    if verbose:
        print '%s attempting: "%s"' % (version,connstr)
    try:
        conn.Open()
    except (Exception), e:
        raise DatabaseError(e) 
Example #2
Source File: testGIT.py    From ironpython2 with Apache License 2.0 7 votes vote down vote up
def DoTestInterpInThread(cookie):
        try:
            pythoncom.CoInitialize()
            myThread = win32api.GetCurrentThreadId()
            GIT = CreateGIT()

            interp = GIT.GetInterfaceFromGlobal(cookie, pythoncom.IID_IDispatch)
            interp = win32com.client.Dispatch(interp)

            TestInterp(interp)
            interp.Exec("import win32api")
            print "The test thread id is %d, Python.Interpreter's thread ID is %d" % (myThread, interp.Eval("win32api.GetCurrentThreadId()"))
            interp = None
            pythoncom.CoUninitialize()
        except:
            traceback.print_exc() 
Example #3
Source File: sampler.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _query_sample_loop(self):
        try:
            # Initialize COM for the current (dedicated) thread
            # WARNING: any python COM object (locator, connection, etc) created in a thread
            # shouldn't be used in other threads (can lead to memory/handle leaks if done
            # without a deep knowledge of COM's threading model).
            pythoncom.CoInitialize()
        except Exception as e:
            self.logger.info("exception in CoInitialize: %s", e)
            raise

        while True:
            self._runSampleEvent.wait()
            if self._stopping:
                self.logger.debug("_query_sample_loop stopping")
                self._sampleCompleteEvent.set()
                return

            self._runSampleEvent.clear()
            if self.is_raw_perf_class and not self._previous_sample:
                self._current_sample = self._query()

            self._previous_sample = self._current_sample
            self._current_sample = self._query()
            self._sampleCompleteEvent.set() 
Example #4
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def AddThread(self, voice, rate, voiceText, suffix, volume, audio):
        pythoncom.CoInitialize()

        if suffix:
            suffix = self.text.suffix + '.' + suffix
        else:
            suffix = self.text.suffix

        tts = self.GetTTS()
        if not tts:
            return
        tts.Voice = self.GetVoice(tts, voice)
        if audio:
            tts.AudioOutput = self.GetAudio(tts, audio)
        tts.Volume = volume
        tts.Rate = rate
        tts_id = pythoncom.CoMarshalInterThreadInterfaceInStream(
            pythoncom.IID_IDispatch,
            tts
        )

        t = Speaker(self, tts_id, voiceText, suffix)
        t.start()
        self.threads.append(t) 
Example #5
Source File: outlook.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def _get_emails():
    pythoncom.CoInitialize()
    outlook = win32com.client.Dispatch('Outlook.Application').GetNameSpace('MAPI')
    inbox   = outlook.GetDefaultFolder(6)
    unread  = inbox.Items
    while True:
        email = None
        try:
            email = unread.GetNext()
        except:
            break
        if email:
            sender   = email.SenderEmailAddress.encode('ascii','ignore')
            message  = email.Body.encode('ascii','ignore')[:100] + '...'
            subject  = email.Subject.encode('ascii','ignore')
            received = str(email.ReceivedTime).replace('/','-').replace('\\','')
            globals()['results'][received] = {'from': sender, 'subject': subject, 'message': message}
        else:
            break 
Example #6
Source File: outlook.py    From byob with GNU General Public License v3.0 6 votes vote down vote up
def _get_emails():
    pythoncom.CoInitialize()
    outlook = win32com.client.Dispatch('Outlook.Application').GetNameSpace('MAPI')
    inbox   = outlook.GetDefaultFolder(6)
    unread  = inbox.Items
    while True:
        email = None
        try:
            email = unread.GetNext()
        except:
            break
        if email:
            sender   = email.SenderEmailAddress.encode('ascii','ignore')
            message  = email.Body.encode('ascii','ignore')[:100] + '...'
            subject  = email.Subject.encode('ascii','ignore')
            received = str(email.ReceivedTime).replace('/','-').replace('\\','')
            globals()['results'][received] = {'from': sender, 'subject': subject, 'message': message}
        else:
            break 
Example #7
Source File: client.py    From canisrufus with GNU General Public License v3.0 5 votes vote down vote up
def _detectServices(self):
        pythoncom.CoInitialize()
        srvs = []
        w = wmi.WMI ()
        for service in w.Win32_Service ():
            srvs.append('{0};{1}'.format(service.Name, str(service.StartMode)))
        return srvs 
Example #8
Source File: outlook.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def count():
    """
    Count unread emails in Outlook inbox
    """
    if len(globals()['results']):
        result = len(globals()['results'])
    else:
        pythoncom.CoInitialize()
        outlook = win32com.client.Dispatch('Outlook.Application').GetNameSpace('MAPI')
        inbox = outlook.GetDefaultFolder(6)
        result = len(inbox.Items)
    return "Emails in Outlook inbox: {}".format(result) 
Example #9
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def get_table_where(self, tname, where={}):
        try:
            pythoncom.CoInitialize()
            c = WMI()
            f = getattr(c, tname)
            return f(**where)
        finally:
            pythoncom.CoUninitialize() 
Example #10
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 #11
Source File: win_os.py    From rpieasy with GNU General Public License v3.0 5 votes vote down vote up
def read_cpu_temp(): 
 try:
  pythoncom.CoInitialize()
  w = wmi.WMI(namespace="root\wmi")
  temperature_info = w.MSAcpi_ThermalZoneTemperature()[0]
  temp = (temperature_info.CurrentTemperature/10.0)-273.15
 except Exception as e:
  temp = 0
 return temp 
Example #12
Source File: win_os.py    From rpieasy with GNU General Public License v3.0 5 votes vote down vote up
def read_cpu_usage():
 try:
  pythoncom.CoInitialize()
  c = wmi.WMI()
  noread = True
  cc = 5
  while noread and cc>0:
   x = [cpu.LoadPercentage for cpu in c.Win32_Processor()]
   cc = cc - 1
   if len(x)>0:
    cc=0
  u = sum(x)/len(x)
 except:
  u = 100
 return u 
Example #13
Source File: win_os.py    From rpieasy with GNU General Public License v3.0 5 votes vote down vote up
def get_memory():
  try:
   m = 0
   pythoncom.CoInitialize()
   comp = wmi.WMI()
   for i in comp.Win32_OperatingSystem():
    m = int(i.FreePhysicalMemory)
  except:
    m = 0
  return m 
Example #14
Source File: client.py    From canisrufus with GNU General Public License v3.0 5 votes vote down vote up
def _detectRunningProcesses(self):
        pythoncom.CoInitialize()
        procs = []
        w = wmi.WMI ()
        for process in w.Win32_Process ():
            procs.append('{0};{1}'.format(process.ProcessId, process.Name))
        return procs 
Example #15
Source File: cis-esp.py    From CIS-ESP with Apache License 2.0 5 votes vote down vote up
def worker(q):
	#importing pythoncom and using CoInitialize() are required to execute WMI commands in threads
	import pythoncom 
	pythoncom.CoInitialize()
	while True:
		host,domainName = q.get() #get the next host from the queue
		runScans(host,domainName) #run the designated scans
		q.task_done() #remove the host from the queue 
Example #16
Source File: client.py    From canisrufus with GNU General Public License v3.0 5 votes vote down vote up
def _detectUsers(self):
        pythoncom.CoInitialize()
        usr = []
        w = wmi.WMI ()
        for user in w.Win32_UserAccount ():
            usr.append('{0};{1};{2}'.format(user.Name, str(AccountType(user.AccountType)).split('.')[1], 'Disabled' if user.Disabled else 'Enabled'))
        return usr 
Example #17
Source File: client.py    From canisrufus with GNU General Public License v3.0 5 votes vote down vote up
def _detectDevices(self):
        pythoncom.CoInitialize()
        devs = []
        w = wmi.WMI ()
        for dev in w.Win32_PnPEntity ():
            devs.append('{0};{1}'.format(dev.Name, dev.Manufacturer))
        return devs 
Example #18
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        pythoncom.CoInitialize()
        tts = win32com.client.Dispatch(
            pythoncom.CoGetInterfaceAndReleaseStream(
                self.tts_id,
                pythoncom.IID_IDispatch
            )
        )

        tts.Speak(self.voiceText, 0)
        self.plugin.TriggerEvent(self.suffix) 
Example #19
Source File: IntegratorControl.py    From PySimulator with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run(self):
        haveCOM = False
        try:
            '''
            Do the numerical integration in a try branch
            to avoid losing the thread when an intended exception is raised
            '''
            try:
                import pydevd
                pydevd.connected = True
                pydevd.settrace(suspend=False)
            except:
                # do nothing, since error message only indicates we are not in debug mode
                pass
            try:
                import pythoncom
                pythoncom.CoInitialize()  # Initialize the COM library on the current thread
                haveCOM = True
            except:
                pass
            self.model.simulate()
        except SimulatorBase.Stopping:
            print("solver canceled ... ")
        except Exception, e:
            print("unexpected error ... ")
            print e 
Example #20
Source File: osdriver.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def initialize():
    logging.root.setLevel(logging.DEBUG)
    fmt = '%(asctime)s.%(msecs)03d %(name)s %(levelname)s %(message)s'
    datefmt = '%H:%M:%S'
    the_handler = logging.handlers.RotatingFileHandler(
        osdriver.mbusb_log_file(), 'a', 1024*1024, 5)
    the_handler.setFormatter(logging.Formatter(fmt, datefmt))
    logging.root.addHandler(the_handler)

    if platform.system() == 'Windows':
        import pythoncom
        pythoncom.CoInitialize() 
Example #21
Source File: outlook.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def search(s):
    """
    Search the emails in the Outlook inbox
    """
    pythoncom.CoInitialize()
    outlook = win32com.client.Dispatch('Outlook.Application').GetNameSpace('MAPI')
    inbox   = outlook.GetDefaultFolder(6)
    emails  = util.emails(inbox.Items)
    for k,v in emails.items():
        if s not in v.get('message') and s not in v.get('subject') and s not in v.get('from'):
            emails.pop(k,v)
    return json.dumps(emails, indent=2) 
Example #22
Source File: outlook.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def installed():
    """
    Check if Outlook is installed on the host machine
    """
    try:
        pythoncom.CoInitialize()
        outlook = win32com.client.Dispatch('Outlook.Application').GetNameSpace('MAPI')
        return True
    except:
        return False 
Example #23
Source File: outlook.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def count():
    """
    Count unread emails in Outlook inbox
    """
    if len(globals()['results']):
        result = len(globals()['results'])
    else:
        pythoncom.CoInitialize()
        outlook = win32com.client.Dispatch('Outlook.Application').GetNameSpace('MAPI')
        inbox = outlook.GetDefaultFolder(6)
        result = len(inbox.Items)
    return "Emails in Outlook inbox: {}".format(result) 
Example #24
Source File: outlook.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def search(s):
    """
    Search the emails in the Outlook inbox
    """
    pythoncom.CoInitialize()
    outlook = win32com.client.Dispatch('Outlook.Application').GetNameSpace('MAPI')
    inbox   = outlook.GetDefaultFolder(6)
    emails  = util.emails(inbox.Items)
    for k,v in emails.items():
        if s not in v.get('message') and s not in v.get('subject') and s not in v.get('from'):
            emails.pop(k,v)
    return json.dumps(emails, indent=2) 
Example #25
Source File: outlook.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def installed():
    """
    Check if Outlook is installed on the host machine
    """
    try:
        pythoncom.CoInitialize()
        outlook = win32com.client.Dispatch('Outlook.Application').GetNameSpace('MAPI')
        return True
    except:
        return False 
Example #26
Source File: process.py    From byob with GNU General Public License v3.0 5 votes vote down vote up
def _monitor(keyword):
    if os.name != 'nt':
        return "Error: Windows platforms only"
    try:
        import wmi
        import pythoncom
        pythoncom.CoInitialize()
        c = wmi.WMI()
        if not len(globals()['log'].getvalue()):
            globals()['log'].write('Time, Owner, Executable, PID, Parent\n')
        process_watcher = c.Win32_Process.watch_for("creation")
        while True:
            try:
                new_process = process_watcher()
                proc_owner = new_process.GetOwner()
                proc_owner = "%s\\%s" % (proc_owner[0], proc_owner[2])
                create_date = new_process.CreationDate
                executable = new_process.ExecutablePath
                pid = new_process.ProcessId
                parent_pid = new_process.ParentProcessId
                row = '"%s", "%s", "%s", "%s", "%s"\n' % (create_date, proc_owner, executable, pid, parent_pid)
                if keyword in row:
                    globals()['log'].write(row)
            except Exception as e1:
                return "{} error: {}".format(monitor.__name__, str(e1))
            if globals()['_abort']:
                break
    except Exception as e2:
        return "{} error: {}".format(monitor.__name__, str(e2)) 
Example #27
Source File: natpunch.py    From p2ptv-pi with MIT License 5 votes vote down vote up
def test(self, upnp_type):
        if DEBUG:
            print >> sys.stderr, 'upnpX: testing UPnP type ' + str(upnp_type)
        if not upnp_type or self.get_ip() is None or upnp_type <= 2 and not win32_imported:
            if DEBUG:
                print >> sys.stderr, 'upnpX: UPnP not supported'
            return 0
        if upnp_type != 3:
            pythoncom.CoInitialize()
        self.upnp = self.upnplist[upnp_type]
        if self.upnp.test():
            if DEBUG:
                print >> sys.stderr, 'upnpX: ok'
            return upnp_type
        if DEBUG:
            print >> sys.stderr, 'upnpX: tested bad'
        return 0 
Example #28
Source File: overview_win.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def get_hardware_info(response):
    pythoncom.CoInitialize()
    win32 = wmi.WMI()

    hardware = response["hardware"]

    hardware.append({Klanguage().to_ts(1011) : [get_cpu_info()]})
    #hardware.append({'Memory' : [""]})
    hardware.append({Klanguage().to_ts(1016) : get_disk_partition(win32)})
    hardware.append({Klanguage().to_ts(1017) : [get_bios_info()]})
    hardware.append({Klanguage().to_ts(1013) : get_gpu_info(win32)})
    hardware.append({Klanguage().to_ts(1012) : get_network_card_info()})

    pythoncom.CoUninitialize() 
Example #29
Source File: client.py    From gdog with GNU General Public License v3.0 5 votes vote down vote up
def _detectDevices(self):
        pythoncom.CoInitialize()
        devs = []
        w = wmi.WMI ()
        for dev in w.Win32_PnPEntity ():
            devs.append('{0};{1}'.format(dev.Name, dev.Manufacturer))
        return devs 
Example #30
Source File: client.py    From gdog with GNU General Public License v3.0 5 votes vote down vote up
def _detectUsers(self):
        pythoncom.CoInitialize()
        usr = []
        w = wmi.WMI ()
        for user in w.Win32_UserAccount ():
            usr.append('{0};{1};{2}'.format(user.Name, str(AccountType(user.AccountType)).split('.')[1], 'Disabled' if user.Disabled else 'Enabled'))
        return usr