def run(self): try: CoInitialize() #this code repeated in lw-gui; put it in a function somewhere c = wmi.WMI() networkAdapters = c.Win32_NetworkAdapter(PhysicalAdapter=True) guidDict = {} for ad in networkAdapters: guidDict[ad.Name] = ad.GUID self.c = wmi.WMI(moniker="//./root/WMI") self.watcher = self.c.MSNdis_StatusMediaConnect.watch_for() except: eventQueue.put(("Status", 'netAdaptersIn', 'Connect: WMI Error')) return eventQueue.put(("Status", 'netAdaptersIn', 'Connect: Active')) self.running = True while self.running == True: try: event = self.watcher(timeout_ms=2000) except wmi.x_wmi_timed_out: continue if event.InstanceName in guidDict.keys() and \ guidDict[event.InstanceName] in fileconfig.config.get('TRIGGERS','adapterConGUIDS').split(';'): eventHandle( 'E_NET_CABLE_IN', "net adapter '%s' gained connection" % event.InstanceName) CoUninitialize() eventQueue.put(("Status", 'netAdaptersIn', 'Connect: Not Running'))
def run(self): try: CoInitialize() self.c = wmi.WMI() self.watcher = self.c.Win32_SystemConfigurationChangeEvent.watch_for( ) #called before devicechangeevent except: eventQueue.put(("Status", 'devices', "Error: WMI Error")) eventQueue.put( ("Log", "Unable to start device monitor: WMI error")) return eventQueue.put(("Status", 'devices', "Active")) self.running = True while self.running == True: try: event = self.watcher(timeout_ms=2000) except wmi.x_wmi_timed_out: continue eventHandle( 'E_DEVICE', "Device Monitor (%s)" % str(deviceMessages[event.EventType])) CoUninitialize() eventQueue.put(("Status", 'devices', "Not Running"))
def _worker(self): CoInitializeEx(COINIT_MULTITHREADED) handler = WithEvents(self.client, EventHandler) handler.setExchange(self) while not self._termination.isSet(): PumpWaitingMessages() self._termination.wait(0.001) CoUninitialize()
def close(self): if self.workbook is not None: self.workbook.Close(SaveChanges=False) self.workbook = None if self.app is not None: self.app.Visible = 0 self.app.Quit() self.app = None CoUninitialize()
def WorkerThread(object): # First step - initialize COM CoInitializeEx(COINIT_MULTITHREADED) this_id = GetCurrentThreadId() that_id = object.GetCurrentThreadId() message = "Thread is %d, and object is on thread %d" % \ (this_id, that_id) print message # Be a good citizen and finalize COM, but # first remove our object references. object = None CoUninitialize()
def run(self): self.running = True self.file_list = [] self.update_progressbar.emit(0) self.clear_textarea.emit() self.update_textarea.emit("Relinking Files in {}\n".format(self.path), self.colors[0]) for root, file in self.excel_files(self.path): self.file_list.append(os.path.join(root, file)) self.update_statusbar.emit('Files Found ' + str(len(self.file_list))) if not self.running: self.update_statusbar.emit('Canceled') return self.update_statusbar.emit('Scanning Completed ' + str(len(self.file_list)) + ' Files Found') total_files = len(self.file_list) current_count = 0 CoInitialize() self.excel = ExcelDocument(visible=False) self.update_statusbar.emit('Starting Excel') for file in self.file_list: current_count += 1 self.update_progressbar.emit( int(float(current_count) / total_files * 100)) self.update_statusbar.emit('Relinking %d of %d' % (current_count, total_files)) self.excel.display_alerts(False) self.excel.open(file, updatelinks=3) color = 0 color += (self.do_search(xlValues) * 1) color += (self.do_search(xlFormulas) * 2) if color > 0: self.do_replace() self.update_textarea.emit(file[len(self.path) + 1:], self.colors[color]) sleep(2) # give it some time to work it's magic self.excel.save() self.excel.close() if not self.running: break self.excel.quit() CoUninitialize() if current_count == total_files: self.update_statusbar.emit('Completed') self.update_progressbar.emit(100) else: self.update_statusbar.emit('Canceled') self.sleep(1)
def _stop_excel(): """Quits Excel if open Example: >>> _stop_excel() """ global xlApp if xlApp is not None: xlApp.Visible = 0 xlApp.Quit() xlApp = None CoUninitialize()
def run(self): CoInitialize() self.c = wmi.WMI() self.watcher = self.c.Win32_VolumeChangeEvent.watch_for() self.running = True while self.running == True: try: event = self.watcher(timeout_ms=2000) except wmi.x_wmi_timed_out: continue eventHandle( 'E_DEVICE', "Volume Monitor (Drive: '%s' Event: '%s')" % (str(event.DriveName), str(deviceMessages[event.EventType]))) CoUninitialize()
def _init(name, subject, facade): #global GD CoInitializeEx(COINIT_MULTITHREADED) def on_data(key, value, action): subject.on_next({'key': key, 'value': value, 'action': action}) # Define events for GlobalDictionary # Note the different function signatures for each event def GD_add(self, key, value, size): #print(f'*Add event for {self.name}* Key {key} added with value {value} -> New size: {size}') on_data(key, value, 'add') def GD_remove(self, key, size): #print(f'*Remove event for {self.name}* Removed key {key}') on_data(key, None, 'remove') def GD_change(self, key, value, size): #print(f'*Change event for {self.name}* Key {key} changed to {value}') on_data(key, value, 'change') def GD_clear(self): for key in GD.keys: GD_remove(self, key, 0) #print(f'*Clear event for {self.name}*') # Create global dictionary with optional events GD = create(name, add=GD_add, remove=GD_remove, change=GD_change, clear=GD_clear) def pump(): # Prevent application from exiting and allow for handling of GlobalDictionary events while True: for chg in facade.get_changes(): GD[chg['key']] = chg['value'] PumpWaitingMessages() time.sleep( 0.01) # Avoids high CPU usage by not checking constantly pump() CoUninitialize()
def run(self): CoInitialize() self.c = wmi.WMI() self.watcher = self.c.Win32_LogicalDisk.watch_for( "creation") #deletion too? self.running = True while self.running == True: try: event = self.watcher(timeout_ms=2000) except wmi.x_wmi_timed_out: continue #if event.DriveType in disksOfInterest: eventHandle( 'E_DEVICE', "Logical disk creation (Drive Name: '%s', Drive type: '%s')" % (event.DeviceID, event.Description)) CoUninitialize()
def PPTtoPDF(inputFileName, outputFileName): res = CoInitializeEx(0) formatType = 32 WithWindow = False powerpoint = comtypes.client.CreateObject("Powerpoint.Application") powerpoint.Visible = 1 if outputFileName[-3:] != 'pdf': outputFileName = outputFileName + ".pdf" if inputFileName and outputFileName: deck = powerpoint.Presentations.Open(inputFileName) deck.SaveAs(outputFileName, formatType) # formatType = 32 for ppt to pdfs deck.Close() powerpoint.Quit() CoUninitialize()
def WorkerThread(object_stream): # First step - initialize COM CoInitialize() # Single-threaded. # Unmarshal the IDispatch object. object = CoGetInterfaceAndReleaseStream( object_stream, IID_IDispatch) # The object we get back is a PyIDispatch, rather # than a friendly Dispatch instance, so we convert # to a usable object. object = Dispatch(object) this_id = GetCurrentThreadId() that_id = object.GetCurrentThreadId() message = "Thread is %d, and object is on thread %d" % \ (this_id, that_id) print message # Be a good citizen and finalize COM, but # first remove our object references. object = None CoUninitialize()
def kill_procs(procs: Union[list, str, int], exclude_pid: int = 0): """Kills processes on Windows Args: :procs: process name, pid, or list of those :exclude_pid: pid to exclude when killing procs """ import win32api from win32com import client from pythoncom import (CoInitializeEx, CoUninitialize, COINIT_MULTITHREADED) if not isinstance(procs, list): procs = [procs] my_pid = win32api.GetCurrentProcessId() CoInitializeEx(COINIT_MULTITHREADED) try: wmg = client.GetObject( r"winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") objLoc = client.Dispatch("wbemscripting.swbemlocator") objLoc.Security_.privileges.addasstring("sedebugprivilege", True) query = r"SELECT * FROM Win32_Process WHERE" for i, procName in enumerate(procs): assert isinstance(procName, (int, str)), f"{procName}" query += r" {}{} = '{}'".format("" if i == 0 else "OR ", "Name" if isinstance( procName, str) else "ProcessID", procName) for proc in wmg.ExecQuery(query): if proc.ProcessID in [my_pid, exclude_pid]: continue proc.Terminate del proc del objLoc del wmg finally: CoUninitialize()
def tts(update, context): filename = datetime.now().strftime("%d%m%y-%H%M%S%f") reply = update.message.reply_to_message if reply is None: text = "".join(context.args) elif reply.text is not None: text = reply.text else: return if len(text) == 0: update.message.reply_text("Type in some text ^^") return update.message.chat.send_action(ChatAction.RECORD_AUDIO) CoInitialize() speak = comtypes.client.CreateObject("SAPI.SpVoice") filestream = comtypes.client.CreateObject("SAPI.spFileStream") filestream.open(path + filename + ".ogg", 3, False) speak.AudioOutputStream = filestream speak.Speak(text) filestream.close() CoUninitialize() with open(path + filename + ".ogg", "rb") as speech: update.message.reply_voice(speech, quote=False) os.remove(path + filename + ".ogg")
def run(self, *args, **kwargs): CoInitializeEx(COINIT_MULTITHREADED) try: return Thread.run(self, *args, **kwargs) finally: CoUninitialize()
def email_outlook_trigger_monitor(): t.sleep(15) while True: range(10000) t.sleep( randrange((round(email_outlook_sleep / 2)), email_outlook_sleep)) if EmailOutlookTrigger.objects.filter(activated=True).exists(): break CoInitialize() email_outlook = win32.dynamic.Dispatch('Outlook.Application') while True: range(10000) t.sleep( randrange((round(email_outlook_sleep / 2)), email_outlook_sleep)) if os.path.exists("logs\\error_log.txt"): break try: email_outlook_trigger_monitor_evaluate(email_outlook) except EmailOutlookDispatchException: print( "Connection to Outlook lost, attempting to restart monitoring..." ) try: email_outlook.Application.Quit() except: pass email_outlook = None del email_outlook CoUninitialize() email_outlook_trigger_monitor() except: with open("logs\\error_log.txt", 'a') as f: try: f.write(traceback.format_exc()) print(traceback.format_exc()) except: pass break if not EmailOutlookTrigger.objects.filter(activated=True).exists(): try: email_outlook.Application.Quit() except: pass email_outlook = None del email_outlook CoUninitialize() email_outlook_trigger_monitor() try: email_outlook.Application.Quit() except: pass email_outlook = None del email_outlook CoUninitialize()
CoInitialize() word = gencache.EnsureDispatch('Word.Application') word.Visible = 0 word.DisplayAlerts = 0 try: doc = word.Documents.Open(docx_path, ReadOnly=1) doc.ExportAsFixedFormat( pdf_path, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) except Exception, e: print(e) finally: word.Quit(constants.wdDoNotSaveChanges) CoUninitialize() def save_doc(fs, docx_path): with open(docx_path) as f: f.write(fs) def ensure_module(): gencache.EnsureModule('{00020905-0000-0000-C000-0000000000046}', 0, 8, 0) def make_sure_file_exist(src_path, max_try_times=10): """ 确保源文件存在,尝试次数最大位10,即10s
def close(self): CoUninitialize() self.initialized = False