def run(self): import pythoncom import win32com.client import win32com pythoncom.CoInitialize() wmi_obj = win32com.client.GetObject("winmgmts:\\root\\cimv2") while not self.event.isSet(): self.in_event.wait() if self.event.isSet(): break for vendor_name, vid in self.vendor_ids: # noinspection PyShadowingNames devices = wmi_obj.ExecQuery( 'Select DeviceID from Win32_SerialPort ' 'where PNPDeviceID like "%' + vid + '%" ' ) coms = [] for device in devices: coms += [device.DeviceID] self._devices = coms self.in_event.clear() self.out_event.set() # noinspection PyPep8,PyBroadException try: pythoncom.CoUninitialize() except: pass self.event.clear() self.in_event.clear() self.out_event.clear() self._thread = None
def excel_catch_screen(filename, sheetname, screen_area, img_name=False): """ 对excel的表格区域进行截图——用例:excel_catch_screen(ur"D:\Desktop\123.xlsx", "Sheet1", "A1:J10")""" pythoncom.CoInitialize() # excel多线程相关 filename = os.path.abspath(filename) excel = DispatchEx("Excel.Application") # 启动excel excel.Visible = True # 可视化 excel.DisplayAlerts = False # 是否显示警告 wb = excel.Workbooks.Open(filename) # 打开excel ws = wb.Sheets(sheetname) # 选择sheet ws.Range(screen_area).CopyPicture() # 复制图片区域 ws.Paste() # 粘贴 ws.Paste(ws.Range('B1')) # 将图片移动到具体位置 name = str(uuid.uuid4()) # 重命名唯一值 new_shape_name = name[:6] excel.Selection.ShapeRange.Name = new_shape_name # 将刚刚选择的Shape重命名,避免与已有图片混淆 ws.Shapes(new_shape_name).Copy() # 选择图片 img = ImageGrab.grabclipboard() # 获取剪贴板的图片数据 if not img_name: img_name = name + ".PNG" img.save(img_name) # 保存图片 wb.Close(SaveChanges=0) # 关闭工作薄,不保存 excel.Quit() # 退出excel pythoncom.CoUninitialize()
def _waiting_queue(self): Log.write("Grinder waiting queue") while self.running: try: if self.command_priority_queue.qsize() > 0: command = self.command_priority_queue.get(True, self.command_queue_timeout) else: command = self.command_queue.get(True, self.command_queue_timeout) except queue.Empty as em: pythoncom.PumpWaitingMessages() continue # idx_level = command_tuple[self.IDX_LEVEL] # command = command_tuple[self.IDX_COMMAND] Log.write("Request Command : " + command.get_tr_name()) if command.get_tr_name() == CM.SHUTDOWN: self._shutdown() pythoncom.CoUninitialize() else: try: self._execute(command) except Exception as ex: Log.write("*EXCEPTION* EXECUTE COMMAND : " + str(ex))
def run(self): log("工作线程开启.") pythoncom.CoInitialize() # 唤起Excel try: app = win32com.client.DispatchEx('Excel.Application') app.Visible = conf["showExcel"] app.DisplayAlerts = 0 except: log("唤起Excel失败.停止运行.\n" + format_exc(), 2) tm.showerror("错误", "无法唤起 \"Excel.Application\",抓取停止\n") return else: log("唤起Excel成功.") # 执行爬取函数 try: getcontent(self, app) except: log("工作线程发生未知错误." + format_exc(), 2) log("试图结束线程.", 1) finally: pythoncom.CoUninitialize() frmPro.grid_remove() frmMain.grid(row=0) try: app.Quit() except: log("关闭Excel失败.请打开任务管理器检查Excel是否已退出." + format_exc(), 2) else: log("Excel已关闭.") log("工作线程已退出.") return None
def ddefunc(datahubname, topic, filename): pythoncom.CoInitialize() xlApp = DispatchEx("Excel.Application") xlApp.Visible = 0 #隐藏 xlApp.Application.DisplayAlerts = 0 #禁止弹出会话 nChan = xlApp.Application.DDEInitiate(datahubname, topic) #datahub名称 arrname = Opentxt(filename).split(",") #tagname timestamp = timefunc() #timestamp ValueResult = [] Jsonlist = [] for i in arrname: repi = i.replace(".value", "") DDEVALUE = xlApp.DDErequest(nChan, i) if not DDEVALUE[0]: pass else: ValueResult.append( Tag(i.replace(".Value", ""), timestamp, str(DDEVALUE[0]))) for tag in ValueResult: Jsonlist.append(eval(json.dumps(tag.__dict__))) xlApp.Quit() pythoncom.CoUninitialize() return Jsonlist
def execute(clsid): clsid = IID(clsid) BaseDefaultPolicy = win32com.server.policy.DefaultPolicy class MyPolicy(BaseDefaultPolicy): def _CreateInstance_(self, reqClsid, reqIID): if reqClsid == clsid: return win32com.server.util.wrap(CommandLoop(), reqIID) else: return BaseDefaultPolicy._CreateInstance_(self, clsid, reqIID) win32com.server.policy.DefaultPolicy = MyPolicy factory = pythoncom.MakePyFactory(clsid) clsctx = pythoncom.CLSCTX_LOCAL_SERVER flags = pythoncom.REGCLS_MULTIPLEUSE | pythoncom.REGCLS_SUSPENDED try: revokeId = pythoncom.CoRegisterClassObject(clsid, factory, clsctx, flags) pythoncom.EnableQuitMessage(win32api.GetCurrentThreadId()) pythoncom.CoResumeClassObjects() pythoncom.PumpMessages() finally: pythoncom.CoRevokeClassObject(revokeId) pythoncom.CoUninitialize()
def get_processes(): pythoncom.CoInitialize() c = wmi.WMI() processes = [] for process in c.Win32_Process(): #print process.ProcessId, process.Name try: owner = process.GetOwner() except: owner = ("Unknown", "Unknown", "Unknown") if process.ProcessId == 0 or process.ProcessId == 4: #print process continue record = prepare_process_record(process, owner) if record: processes.append(record) pythoncom.CoUninitialize() return processes
def main(file: string): list_of_bad_cols = [ 'CREATION_USERID', 'LAST_UPD_USERID', 'LAST_UPD_TMSTMP', 'CREATION_TMSTMP' ] excel = win32.gencache.EnsureDispatch('Excel.Application') excel.Visible = 0 file_path = os.path.join(os.getcwd(), file) wb = excel.Workbooks.Open(file_path) for i in range(1, wb.Sheets.Count + 1): ws = wb.Worksheets(i) # This bit is magic to get total number of cols in a given worksheet # DO NOT TOUCH xl_to_left = -4159 col_count = ws.Cells(1, ws.Columns.Count).End(xl_to_left).Column # Since we are deleting columns (which shifts the column index left) the index of the columns # is not constant. Thus we must only increase the starting index if we do not delete a column. # This can possibly lead to an infinite loop. PLEASE BE CAREFUL MODIFYING # TODO: see if there's a better way to write this code col_idx = 1 while col_idx < col_count + 1: col_heading = ws.Cells(1, col_idx).Value if col_heading and any(x in col_heading.strip() for x in list_of_bad_cols): ws.Columns(col_idx).Delete() col_count -= 1 continue else: col_idx += 1 # TODO: see if I actually need all four of these lines to quit Excel wb.Close(True) excel.Application.Quit() pythoncom.CoUninitialize() del excel
def update_thread_handler(self) -> None: logging.info("update_thread_handler start") try: pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.async_loop = loop self.update_message_queue = asyncio.Queue(loop=self.async_loop) self.send_message_queue = asyncio.Queue(loop=self.async_loop) self.ready_to_send = asyncio.Event(loop=self.async_loop) # Following call can cause deadlock if mainthread is not pumping Windows message. self.SetCallbackThread() update_msg_coro = self._update_msg_handler() send_msg_coro = self._send_msg_handler() loop.run_until_complete(asyncio.gather(update_msg_coro, send_msg_coro)) loop.close() except Exception as e: logging.error("update_thread_handler: {}".format(repr(e))) finally: pythoncom.CoUninitialize()
def closeCom(self): pythoncom.CoUninitialize()
def couninit(): pythoncom.CoUninitialize()
def WorkerThreadEnding(self): pythoncom.CoUninitialize()
def closeCom(self): pythoncom.CoUninitialize() self.dcApplication = None self.dcDocuments = None self.dcDocument = None
def get(file_name): path = os.path.join(globaldefines.path, file_name) tasks = [] errs = [] try: state = State.Init pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) state = State.CoInitialize globaldefines.other_trace('%s get state = %s' % (file_name, state)) project_exe = win32com.client.DispatchEx("MSProject.Application") project_exe.Visible = False project_exe.DisplayAlerts = False state = State.DispatchEx globaldefines.other_trace('%s get state = %s' % (file_name, state)) project_exe.FileOpenEx(Name=path, ReadOnly=True) count = project_exe.Projects.count project_tasks = project_exe.Projects.item(path).tasks state = State.FileOpenEx globaldefines.other_trace('%s get state = %s(%s)' % (file_name, state, str(count))) for project_task in project_tasks: task = { ProjectFile.DESCRIPTION_INDEX: str(project_task.ID), ProjectFile.DESCRIPTION_CHAPTER: str(project_task.WBS), ProjectFile.DESCRIPTION_STARTTIME: round(float('%.2f' % project_task.Number6) * 100), ProjectFile.DESCRIPTION_ENDTIME: round(float('%.2f' % project_task.Number7) * 100), ProjectFile.DESCRIPTION_CMD: str(project_task.Name).strip().upper(), ProjectFile.DESCRIPTION_PARAM1: int(project_task.Number1), ProjectFile.DESCRIPTION_PARAM2: int(project_task.Number2), ProjectFile.DESCRIPTION_PARAM3: int(project_task.Number3), ProjectFile.DESCRIPTION_PARAM4: int(project_task.Number4) } tasks.append(task) state = State.Done globaldefines.other_trace('%s get state = %s\n\t%s' % (file_name, state, str(tasks))) except Exception as e: globaldefines.other_trace("Except: other except %s" % str(e)) if state >= State.FileOpenEx: errs.append('file read error') elif state >= State.DispatchEx: errs.append('project open error') elif state >= State.CoInitialize: errs.append('init com environment fail') except BaseException as e: globaldefines.other_trace("Except: other except %s" % str(e)) raise e finally: globaldefines.other_trace("%s get finally state = %s" % (file_name, state)) if state >= State.FileOpenEx: project_exe.FileCloseEx(Save=0) if state >= State.DispatchEx: project_exe.Quit(SaveChanges=0) if state >= State.CoInitialize: pythoncom.CoUninitialize() globaldefines.other_trace("%s get return" % file_name) return tasks, errs
def __del__(self): self._project_exe.FileCloseAllEx(Save=0) self._project_exe.Quit(SaveChanges=0) pythoncom.CoUninitialize()
BaseDefaultPolicy = win32com.server.policy.DefaultPolicy class MyPolicy(BaseDefaultPolicy): def _CreateInstance_(self, reqClsid, reqIID): if reqClsid == clsid: return serverutil.wrap(XLPython(), reqIID) print reqClsid else: return BaseDefaultPolicy._CreateInstance_(self, clsid, reqIID) win32com.server.policy.DefaultPolicy = MyPolicy # --- create the class factory and register it factory = pythoncom.MakePyFactory(clsid) clsctx = pythoncom.CLSCTX_LOCAL_SERVER flags = pythoncom.REGCLS_MULTIPLEUSE | pythoncom.REGCLS_SUSPENDED revokeId = pythoncom.CoRegisterClassObject(clsid, factory, clsctx, flags) pythoncom.EnableQuitMessage(win32api.GetCurrentThreadId()) pythoncom.CoResumeClassObjects() pythoncom.PumpMessages() pythoncom.CoRevokeClassObject(revokeId) pythoncom.CoUninitialize()
def networkobjet(self, sessionid, action): self.messagejson = {} self.messagejson['action'] = action self.messagejson['sessionid'] = sessionid self.messagejson['listdns'] = [] self.messagejson['listipinfo'] = [] self.messagejson['dhcp'] = 'False' self.messagejson['dnshostname'] = '' self.messagejson['msg'] = platform.system() try: self.messagejson['users'] = self.getuser() except BaseException: self.messagejson['users'] = ["system"] if sys.platform.startswith('linux'): p = subprocess.Popen( "ps aux | grep dhclient | grep -v leases | grep -v grep | awk '{print $NF}'", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) result = p.stdout.readlines() if len(result) > 0: self.messagejson['dhcp'] = 'True' else: self.messagejson['dhcp'] = 'False' self.messagejson['listdns'] = self.listdnslinux() self.messagejson['listipinfo'] = self.getLocalIipAddress() self.messagejson['dnshostname'] = platform.node() return self.messagejson elif sys.platform.startswith('win'): """ revoit objet reseau windows """ pythoncom.CoInitialize() try: wmi_obj = wmi.WMI() wmi_sql = "select * from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE" wmi_out = wmi_obj.query(wmi_sql) finally: pythoncom.CoUninitialize() for dev in wmi_out: objnet = {} objnet['macaddress'] = dev.MACAddress objnet['ipaddress'] = dev.IPAddress[0] try: objnet['gateway'] = dev.DefaultIPGateway[0] except BaseException: objnet['gateway'] = "" objnet['mask'] = dev.IPSubnet[0] objnet['dhcp'] = dev.DHCPEnabled objnet['dhcpserver'] = dev.DHCPServer self.messagejson['listipinfo'].append(objnet) try: self.messagejson['listdns'].append( dev.DNSServerSearchOrder[0]) except BaseException: pass self.messagejson['dnshostname'] = dev.DNSHostName self.messagejson['msg'] = platform.system() return self.messagejson elif sys.platform.startswith('darwin'): return self.MacOsNetworkInfo() else: self.messagejson[ 'msg'] = "system %s : not managed yet" % sys.platform return self.messagejson
def decorator(*args, **kwargs): pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) try: return fn(*args, **kwargs) finally: pythoncom.CoUninitialize()
def __exit__(self, exc_type, exc_value, traceback): if self.need_com_init: log.debug('Uninitializing COM library') pythoncom.CoUninitialize()
def WinUninitialize(): if platform.system() == 'Windows': import pythoncom pythoncom.CoUninitialize()
def liquidacion_acceso(request,pk,id_liquidacion): liquidacion = LiquidacionGestor.objects.get(id=id_liquidacion) pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED) xl = win32com.client.dynamic.Dispatch('Word.Application') xl.DisplayAlerts = False xl.Visible = 0 archivo = xl.Documents.Open(settings.STATICFILES_DIRS[0]+'/formatos/Formato de liquidaciones.docx') archivo.Sections(1).Headers(1).Range.InsertAfter(liquidacion.gestor.nombre.decode('UTF-8').upper()+"\r\r") tabla = archivo.Tables(1) tabla.Cell(Row=1,Column=2).Range.Text = liquidacion.gestor.nombre.decode('UTF-8').upper() if liquidacion.gestor.region.id == 1: region = "Región Uno (1) Amazonas, Arauca, Caquetá, Casanare, Guainía, Guaviare, Huila, Meta, Putumayo, Tolima, Vaupés, Vichada".decode('UTF-8') if liquidacion.gestor.region.id == 2: region = "Región Cuatro (4) Bogotá D.C., Boyacá, Cundinamarca, Norte de Santander, Santander".decode('UTF-8') tabla.Cell(Row=2,Column=2).Range.Text = region tabla.Cell(Row=3,Column=2).Range.Text = liquidacion.gestor.cedula objeto = tabla.Cell(Row=4,Column=2).Range.Text objeto = objeto.replace("%REGION%",region) tabla.Cell(Row=4,Column=2).Range.Text = objeto tabla.Cell(Row=5,Column=2).Range.Text = Money(liquidacion.valor_ejecutado,'COP').format('es_CO','$#,##0.00')+" Mcte" tabla.Cell(Row=7,Column=2).Range.Text = str(int((liquidacion.valor_ejecutado*100.0)/liquidacion.valor_inicial))+" %" if liquidacion.gestor.fecha_contratacion != None: tabla.Cell(Row=8,Column=2).Range.Text = liquidacion.gestor.fecha_contratacion.strftime("%d/%m/%Y") if liquidacion.fecha_terminacion != None: tabla.Cell(Row=9,Column=2).Range.Text = liquidacion.fecha_terminacion.strftime("%d/%m/%Y") meses = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"] mes = int(liquidacion.gestor.fecha_contratacion.strftime("%m"))-1 fecha = liquidacion.gestor.fecha_contratacion.strftime("%d de "+meses[mes]+" de %Y") tabla = archivo.Tables(2) tabla.Cell(Row=1,Column=2).Range.Text = fecha tabla = archivo.Tables(3) tabla.Cell(Row=1,Column=1).Range.Text = liquidacion.gestor.nombre.decode('UTF-8').upper() tabla.Cell(Row=1,Column=3).Range.Text = liquidacion.gestor.cedula tabla = archivo.Tables(4) tabla.Cell(Row=1,Column=2).Range.Text = liquidacion.contrato tabla.Cell(Row=1,Column=4).Range.Text = fecha tabla = archivo.Tables(5) tabla.Cell(Row=1,Column=2).Range.Text = fecha tabla = archivo.Tables(6) tabla.Cell(Row=1,Column=1).Range.Text = liquidacion.gestor.nombre.decode('UTF-8').upper() tabla.Cell(Row=1,Column=3).Range.Text = liquidacion.gestor.cedula tabla = archivo.Tables(7) tabla.Cell(Row=1,Column=1).Range.Text = "GESTOR TERRITORIAL" tabla = archivo.Tables(8) tabla.Cell(Row=1,Column=1).Range.Text = "para Educar para el periodo 2015 en la "+region tabla = archivo.Tables(9) tabla.Cell(Row=1,Column=1).Range.Text = fecha tabla = archivo.Tables(10) tabla.Cell(Row=1,Column=2).Range.Text = Money(liquidacion.valor_inicial,'COP').format('es_CO','$#,##0.00') tabla.Cell(Row=2,Column=3).Range.Text = Money(liquidacion.valor_ejecutado,'COP').format('es_CO','$#,##0.00') tabla.Cell(Row=3,Column=3).Range.Text = Money(liquidacion.valor_pagado,'COP').format('es_CO','$#,##0.00') if liquidacion.valor_ejecutado-liquidacion.valor_pagado >= 0: tabla.Cell(Row=4,Column=3).Range.Text = Money(liquidacion.valor_ejecutado-liquidacion.valor_pagado,'COP').format('es_CO','$#,##0.00') tabla.Cell(Row=5,Column=3).Range.Text = Money(0,'COP').format('es_CO','$#,##0.00') else: tabla.Cell(Row=4,Column=3).Range.Text = Money(0,'COP').format('es_CO','$#,##0.00') tabla.Cell(Row=5,Column=3).Range.Text = Money(liquidacion.valor_pagado-liquidacion.valor_ejecutado,'COP').format('es_CO','$#,##0.00') tabla = archivo.Tables(11) tabla.Cell(Row=1,Column=2).Range.Text = Money(liquidacion.valor_ejecutado-liquidacion.valor_pagado,'COP').format('es_CO','$#,##0.00') tabla = archivo.Tables(12) tabla.Cell(Row=1,Column=2).Range.Text = liquidacion.gestor.nombre.decode('UTF-8').upper() tabla.Cell(Row=2,Column=1).Range.Text = liquidacion.gestor.cedula tabla.Cell(Row=3,Column=2).Range.Text = liquidacion.contrato tabla.Cell(Row=4,Column=2).Range.Text = fecha+"." mes = int(datetime.date.today().strftime("%m"))-1 fecha2 = datetime.date.today().strftime("%d dias del mes de "+meses[mes]+" de %Y") tabla = archivo.Tables(13) tabla.Cell(Row=1,Column=1).Range.Text = fecha2+"." tabla = archivo.Tables(14) tabla.Cell(Row=1,Column=2).Range.Text = liquidacion.gestor.nombre.decode('UTF-8').upper() tabla.Cell(Row=2,Column=2).Range.Text = "C.C.No "+str(liquidacion.gestor.cedula) archivo.SaveAs('C:\\Temp\\Liquidacion '+liquidacion.gestor.nombre.decode('UTF-8')+'.docx') archivo.Close(SaveChanges=False) xl.Quit() pythoncom.CoUninitialize() zip_subdir = liquidacion.gestor.nombre.decode('UTF-8') zip_filename = "%s.zip" % zip_subdir s = StringIO.StringIO() zf = zipfile.ZipFile(s, "w") path = 'C:\\Temp\\Liquidacion '+liquidacion.gestor.nombre.decode('UTF-8')+'.docx' if os.path.exists(path): fdir, fname = os.path.split(path) zf.write(path,os.path.join(liquidacion.gestor.nombre.decode('UTF-8'),fname)) zf.close() os.remove(path) resp = HttpResponse(s.getvalue(), content_type = "application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename return resp
def ThreadWorker(self, stopThreadEvent): pythoncom.CoInitialize() self.cntr = 0 #Attach interface to the OCX AxkmkusbT = None try: AxkmkusbT = win32com.client.Dispatch("KMKUSB5I8OOCX.KMKUSB") except: raise eg.Exception(self.b_nbr, self.text.txt_OCX_CannotBeFound_T) if AxkmkusbT != None: print self.b_nbr, self.text.txt_OCX_Found_T #Address the board... AxkmkusbT.device = self.b_nbr print self.b_nbr, self.text.txt_Initiated #Open the port AxkmkusbT.port_open_close = 1 time.sleep(0.9) #Set outputs to last known states if self.kmkSum != self.kmkSum_trigger: AxkmkusbT.out = str(self.kmkSum) print self.b_nbr, self.text.txt_InitOut, self.kmkSum self.kmkSum_trigger = self.kmkSum time.sleep(0.9) while not stopThreadEvent.isSet(): inputs = str(AxkmkusbT.binary) if inputs != "": inputList = [] for i in range(0, len(inputs)): inputList.insert(i, inputs[i]) for i in range(0, len(inputs)): ret = int(inputList[i]) if ret != self.di_event_trigger[i]: if self.di_event_memory[i] != ret: self.TriggerEvent(self.b_nbr + ":" + self.text.txt_DI + str(i + 1) + self.text.txt_State + str(ret)) del self.di_event_memory[i] self.di_event_memory.insert(i, ret) if self.di_event_memory[i] != ret: self.TriggerEvent(self.b_nbr + ":" + self.text.txt_DI + str(i + 1) + self.text.txt_State + str(ret)) del self.di_event_memory[i] self.di_event_memory.insert(i, ret) else: #The board is not responding if self.cntr == 9: self.cntr = 0 if self.cntr == 0: self.TriggerEvent(self.text.txt_boardError + str(self.b_nbr)) self.cntr += 1 print self.cntr stopThreadEvent.wait(1.0) AxkmkusbT = None try: AxkmkusbT = win32com.client.Dispatch( "KMKUSB5I8OOCX.KMKUSB") except: raise eg.Exception(self.b_nbr, self.text.txt_OCX_CannotBeFound_T) AxkmkusbT.device = self.b_nbr AxkmkusbT.port_open_close = 1 time.sleep(0.9) inputs = str(AxkmkusbT.binary) print inputs if inputs != "": self.TriggerEvent(self.text.txt_boardOK + str(self.b_nbr)) self.cntr = 0 AxkmkusbT.out = str(self.kmkSum_trigger) print self.b_nbr, self.text.txt_InitOut, self.kmkSum if self.kmkSum != self.kmkSum_trigger: AxkmkusbT.out = str(self.kmkSum_trigger) print self.b_nbr, self.text.txt_OutSent, self.kmkSum_trigger self.kmkSum = self.kmkSum_trigger # print self.b_nbr, self.di_event_trigger # print self.b_nbr, self.di_event_memory # print self.b_nbr, self.do_state_memory #Test to see what gets sent. # print self.b_nbr, self.text.txt_OutSet, str(self.kmkSum) stopThreadEvent.wait(self.thread_wait) AxkmkusbT.port_open_close = 0 pythoncom.CoUninitialize() print self.b_nbr, self.text.txt_Polling
def run(self): pythoncom.CoInitialize() self.rst = self.func(*self.params, **self.paramMap) self.finished = True pythoncom.CoUninitialize()
def __exit__(self, _type, _value, _traceback): pythoncom.CoUninitialize()
def appActivate(app): pythoncom.CoInitialize() shell = win32com.client.Dispatch("WScript.Shell") pythoncom.CoUninitialize() return shell.AppActivate(app)
def run(self): global exit_threads print "Starting USB monitor" pythoncom.CoInitialize() # instantiate the WMI interface c = wmi.WMI() while not exit_threads: try: #watch for USB insertions watcher1 = c.watch_for(notification_type="Creation", wmi_class="Win32_USBControllerDevice") watcher2 = c.watch_for(notification_type="Deletion", wmi_class="Win32_USBControllerDevice") while True: try: usb = watcher1(timeout_ms=4000) device_id = get_device_id(usb) for elem in wmi.WMI().Win32_PnPEntity(): if device_id == elem.DeviceID: #print elem usb_info = get_usb_class(elem) usb_class = 0x0 if usb_info: usb_class = usb_info[0] if usb_class == 0x8 or \ 'USBSTOR' in elem.DeviceID: print 'Mass Storage Connected: Skiping' self.mass_storage_list.append( elem.DeviceID) continue self.created_pnp_entities.append(elem) except wmi.x_wmi_timed_out: if self.created_pnp_entities: devices = split_usb_devices( self.created_pnp_entities) for device in devices: usb_classes = set() captions = set() device_ids = set() for elem in devices[device]: usb_info = get_usb_class(elem) # usb_cls value can be 0 so we can't just use if usb_cls if usb_info != None: usb_classes.add(usb_info) if elem.Caption: captions.add(elem.Caption) vid, pid = device process_usb_record("Insertion", vid, pid, list(usb_classes), list(captions)) self.created_pnp_entities = [] try: usb = watcher2(timeout_ms=4000) device_id = get_device_id(usb) if device_id not in self.mass_storage_list: #print usb self.deleted_devices.add(get_vid_pid(device_id)) else: self.mass_storage_list.remove(device_id) except wmi.x_wmi_timed_out: if self.deleted_devices: for device in self.deleted_devices: if device: #print device vid, pid = device process_usb_record("Deletion", vid, pid) self.deleted_devices = set() except KeyboardInterrupt: exit_threads = True print "1" raise except: print "USBMonitor - Exception: " + str(sys.exc_info()) raise finally: pythoncom.CoUninitialize()
def testall(): dotestall() pythoncom.CoUninitialize() print("AXScript Host worked correctly - %d/%d COM objects left alive." % ( pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount()))
def get_a_signal(self, signal_queue, gui_queue, result_queue, oecon_list=None, ts_instance=None, can_bus=2, signal="EmgcyCallHmi_D_Stat", msg="TCU_Send_Signals_5", enum=None, verify_queue=None): """ Select one signal to monitor and pass to ts_instance. :param ts_instance: Choose test suite :param signal_queue: Pass signal values to test suite instance. tuple (signal_status, delta_time) :param gui_queue: Update GUI :param can_bus: CAN BUS Channel :param oecon_list: oecon info, passed to ts_instance :param signal: signal user defined :param msg: signal related message :param enum: if not None, it should be related to the signal. :return: """ pythoncom.CoInitialize() self.app = win32com.client.Dispatch( pythoncom.CoGetInterfaceAndReleaseStream(self.marshalled_app_id, pythoncom.IID_IDispatch)) temp_status = -10.0 prev_time = time.time() count_1 = 0 while True: time.sleep(0.1) current_status = self.app.Bus.GetSignal(can_bus, msg, signal).RawValue if temp_status != current_status: count_1 += 1 current_time = time.time() delta_time, prev_time = current_time - prev_time, current_time temp_status = current_status # print "current status put to queue:", current_status signal_queue.put((current_status, delta_time)) if verify_queue: verify_queue.put((current_status, delta_time)) if enum: for name, member in enum.__members__.items(): if current_status == member.value: current_status = member else: # if not implemented in enum, should convert integer to readable CAN msg values. current_status = help_utils.decode_raw_signal_value_helper( current_status) gui_queue.put( str(current_status) + " is changed in " + str(delta_time) + "s.") # pass signal value to test suite if ts_instance: ts_instance.ts_start(signal_queue, gui_queue, result_queue, oecon_list) if self.event.wait(timeout=0.01): pythoncom.CoUninitialize() break
def deinitPerThread(self): import pythoncom pythoncom.CoUninitialize()
def get_all_signals(self, queue_from_gui, signal_enum_1, signal_1, message_1, signal_enum_2=can_signals_enum.IgnStatus, signal_2="Ignition_Status", message_2="BodyInfo_3_HS4"): pythoncom.CoInitialize() self.app = win32com.client.Dispatch( pythoncom.CoGetInterfaceAndReleaseStream(self.marshalled_app_id, pythoncom.IID_IDispatch)) temp_status = -10.0 temp_status_2 = -10.0 prev_time = time.time() prev_time_2 = time.time() signal_delta_log_1 = list() signal_delta_log_1.append("\n" + signal_enum_1.name() + " status: ") # signal_delta_log_1.append(signal_enum_1.name() + " status: default -> ") signal_delta_log_2 = list() signal_delta_log_2.append("\n" + signal_enum_2.name() + " status: ") # signal_delta_log_2.append(signal_enum_2.name() + " status: default -> ") signal_current_log_1 = list() signal_current_log_1.append(signal_enum_1.name() + " status: ") # signal_current_log_1.append(signal_enum_1.name() + " status: default") signal_current_log_2 = list() signal_current_log_2.append(signal_enum_2.name() + " status: ") # signal_current_log_2.append(signal_enum_2.name() + " status: default") count_1 = 0 while True: time.sleep(1) current_status = self.app.Bus.GetSignal(2, message_1, signal_1).Value # signal_current_log_1.append("oh " + signal_enum_1.name() + " status: " + str(current_status)) if temp_status != current_status: count_1 += 1 current_time = time.time() delta_time, prev_time = current_time - prev_time, current_time temp_status = current_status for name, member in signal_enum_1.__members__.items(): if current_status == member.value: current_status = member queue_from_gui.put( "curr status: {} and delta time: {} at: {}".format( current_status, delta_time, current_time)) print( "curr status: {} and delta time: {} at: {}".format( current_status, delta_time, current_time)) signal_delta_log_1.append( str(delta_time) + " s -> " + str(current_status) + " -> " + "({})\n".format(count_1)) signal_current_log_1.append(" -> " + str(current_status) + " at: " + str(current_time) + "({})\n".format(count_1)) # self.can_logs.append(" -> " + str(current_status) + " at: " + str(current_time) + "\n") current_status_2 = self.app.Bus.GetSignal(2, message_2, signal_2).Value # signal_current_log_2.append("oh" + signal_enum_2.name() + " status: " + str(current_status_2)) # by default it's ign status if temp_status_2 != current_status_2: current_time_2 = time.time() delta_time_2, prev_time_2 = current_time_2 - prev_time_2, current_time_2 temp_status_2 = current_status_2 for name, member in signal_enum_2.__members__.items(): if current_status_2 == member.value: current_status_2 = member queue_from_gui.put( "curr status: {} and delta time: {} at: {}".format( current_status_2, delta_time_2, current_time_2)) print( "curr status: {} and delta time: {} at: {}".format( current_status_2, delta_time_2, current_time_2)) signal_delta_log_2.append( str(delta_time_2) + " s -> " + str(current_status_2) + " -> " + "\n") signal_current_log_2.append(" -> " + str(current_status_2) + " at: " + str(current_time_2) + "\n") # self.can_logs.append(" -> " + str(current_status_2) + "at: " + str(current_time_2) + "\n") if self.event.wait(timeout=0.01): # print("received stop: {}".format(time.ctime())) # 4) 15:31:20 if not self.delta_flag: if self.can_logs is not None: self.can_logs = self.can_logs + signal_current_log_1 + signal_current_log_2 print("get current") else: if self.can_logs is not None: self.can_logs = self.can_logs + signal_delta_log_1 + signal_delta_log_2 self.can_logs.append('\n') print("get delta") pythoncom.CoUninitialize() break