def demo(delay=1000, stop=10): g = glork(delay, stop) # Timers are message based - so we need # To run a message loop while waiting for our timers # to expire. start_time = time.time() while 1: # We can't simply give a timeout of 30 seconds, as # we may continouusly be recieving other input messages, # and therefore never expire. rc = win32event.MsgWaitForMultipleObjects( (g.event, ), # list of objects 0, # wait all 500, # timeout win32event.QS_ALLEVENTS, # type of input ) if rc == win32event.WAIT_OBJECT_0: # Event signalled. break elif rc == win32event.WAIT_OBJECT_0 + 1: # Message waiting. if win32gui.PumpWaitingMessages(): raise RuntimeError("We got an unexpected WM_QUIT message!") else: # This wait timed-out. if time.time() - start_time > 30: raise RuntimeError( "We timed out waiting for the timers to expire!")
def MessagePump(timeout): waitables = [StopEvent] while 1: rc = win32event.MsgWaitForMultipleObjects( waitables, 0, # Wait for all = false, so it waits for anyone timeout, #(or win32event.INFINITE) win32event.QS_ALLEVENTS) # Accepts all input if rc == win32event.WAIT_OBJECT_0: # Our first event listed, the StopEvent, was triggered, so we must exit print('stop event') break elif rc == win32event.WAIT_OBJECT_0 + len(waitables): # A windows message is waiting - take care of it. (Don't ask me # why a WAIT_OBJECT_MSG isn't defined < WAIT_OBJECT_0...!). # This message-serving MUST be done for COM, DDE, and other # Windowsy things to work properly! print('pump') if pythoncom.PumpWaitingMessages(): break # we received a wm_quit message elif rc == win32event.WAIT_TIMEOUT: print('timeout') return pass else: print('exception') raise RuntimeError("unexpected win32wait return value")
def run(self): continueloop = True n = 1 waitingOnRead = False buf = win32file.AllocateReadBuffer(n) while continueloop: if self.EVENT.isSet(): win32event.SetEvent(self.stopevent) if not waitingOnRead: win32event.ResetEvent(self.serial._overlappedRead.hEvent) hr, _ = win32file.ReadFile(self.serial.hComPort, buf, self.serial._overlappedRead) if hr == 997: waitingOnRead = True elif hr == 0: pass else: raise rc = win32event.MsgWaitForMultipleObjects((self.serial._overlappedRead.hEvent, self.stopevent), 0, 1000, win32event.QS_ALLINPUT) if rc == win32event.WAIT_OBJECT_0: n = win32file.GetOverlappedResult(self.serial.hComPort, self.serial._overlappedRead, 1) if n and not self.EVENT.isSet(): self.plugin.Decode(ord(buf[0])) waitingOnRead = False elif rc == win32event.WAIT_OBJECT_0+1: continueloop = False elif rc == win32event.WAIT_TIMEOUT: pass else: pass self.serial.close()
def _pump_messages(self): """Handle messages from the Windows message loop. Returns `False` when process should stop. Notes: - WAIT_OBJECT_0 refers to the first item in given waitables - WAIT_OBJECT_0 + len(waitables) refers to a message defined by the mask, i.e. QS_ALLEVENTS """ waitables = [self.STOP_EVENT] event = win32event.MsgWaitForMultipleObjects( waitables, False, 100, win32event.QS_ALLEVENTS, ) if event == win32event.WAIT_OBJECT_0: return False if event == win32event.WAIT_OBJECT_0 + len(waitables): win32gui.PumpWaitingMessages() return True if event == win32event.WAIT_TIMEOUT: return True raise RuntimeError(f"Unexpected event: {event}")
def _DoTestMarshal(self, fn, bCoWait=0): #print "The main thread is %d" % (win32api.GetCurrentThreadId()) threads, events = fn(2) numFinished = 0 while 1: try: if bCoWait: rc = pythoncom.CoWaitForMultipleHandles(0, 2000, events) else: # Specifying "bWaitAll" here will wait for messages *and* all events # (which is pretty useless) rc = win32event.MsgWaitForMultipleObjects( events, 0, 2000, win32event.QS_ALLINPUT) if rc >= win32event.WAIT_OBJECT_0 and rc < win32event.WAIT_OBJECT_0 + len( events): numFinished = numFinished + 1 if numFinished >= len(events): break elif rc == win32event.WAIT_OBJECT_0 + len(events): # a message # This is critical - whole apartment model demo will hang. pythoncom.PumpWaitingMessages() else: # Timeout print "Waiting for thread to stop with interfaces=%d, gateways=%d" % ( pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount()) except KeyboardInterrupt: break for t in threads: t.join(2) self.failIf(t.isAlive(), "thread failed to stop!?") threads = None # threads hold references to args
def test(fn): print("The main thread is %d" % (win32api.GetCurrentThreadId())) GIT = CreateGIT() interp = win32com.client.Dispatch("Python.Interpreter") cookie = GIT.RegisterInterfaceInGlobal(interp._oleobj_, pythoncom.IID_IDispatch) events = fn(4, cookie) numFinished = 0 while 1: try: rc = win32event.MsgWaitForMultipleObjects(events, 0, 2000, win32event.QS_ALLINPUT) if rc >= win32event.WAIT_OBJECT_0 and rc < win32event.WAIT_OBJECT_0 + len( events): numFinished = numFinished + 1 if numFinished >= len(events): break elif rc == win32event.WAIT_OBJECT_0 + len(events): # a message # This is critical - whole apartment model demo will hang. pythoncom.PumpWaitingMessages() else: # Timeout print( "Waiting for thread to stop with interfaces=%d, gateways=%d" % (pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount())) except KeyboardInterrupt: break GIT.RevokeInterfaceFromGlobal(cookie) del interp del GIT
def _MessagePump(): waitable = StopEvent, OtherEvent while True: rc = win32event.MsgWaitForMultipleObjects( waitables, #Wait for all = false 所以现在它等待任意一个 TIMEOUT, #或win32event.INFINITE win32event.QS_ALLEVENTS) #接受各种事件 #可以在这里调用函数,如果它花的时间不长的话,至少每TIMEOUT毫秒 #它被执行一次——还可能更频繁 #具体取决于收到的Windows消息的数目 if rc == win32event.WAIT_OBJECT_0: #所以我们第一个列表中的事件,StopEvent被激发所以我们必须退出,终止消息泵 break elif rc == win32event.WAIT_OBJECT_0 + 1: #我们的第二个列表中的事件,OhterEvent被设置 #做任何需要做的事情即可,可以根据需要 #等待任意多的内核对象(事件、锁、进程、线程、通知等等) pass elif rc == win32event.WAIT_OBJECT_0 + len(waitables): #一个Windows消息在等待——处理之(别问我为什么WAIT_OBJECT_MSG没被定义 < WAIT_OBJECT_0...!) #这种消息服务是COM、DDE,以及其他Windows组件正常工作的重要保障 if pythoncom.PumpWaitingMessage(): break #收到了一个wm_quit消息 elif rc == win32event.WAIT_TIMEOUT: #超时了 #我们在这里做点事 pass else: raise RuntimeError("unexpected win32wait return value")
def com_poll(self): # check every 100ms for new events reactor.callLater(0.10, self.com_poll) pythoncom.CoInitialize() rc = win32event.MsgWaitForMultipleObjects( (win32event.CreateEvent(None, 0, 0, None), ), 0, 0, win32event.QS_ALLEVENTS) if rc == win32event.WAIT_OBJECT_0: reactor.stop() pythoncom.PumpWaitingMessages()
def wait_and_pump_msg(timeout=5, done_time=5000): """ :param timeout: :param done_time: :return: """ # timeout in seconds, dontime in milliseconds! ''' # !!!!!!!!!!!!!! IMPORTANT to make CANalyzer not FREEZE!!!!! # pythoncom.PumpWaitingMessages() from win32process import beginthreadex from win32event import MsgWaitForMultipleObjects, QS_ALLINPUT, WAIT_OBJECT_0,CreateEvent # handle, ids = beginthreadex(None, 0, sleep_thread, (), 0) # handles = list() # handles.append(handle) ic_event_handle = CreateEvent(None,0,0,None) rc = MsgWaitForMultipleObjects((ic_event_handle,), 0, 5000, QS_ALLINPUT) start_time = time.time() while True: if rc == WAIT_OBJECT_0 + 1: pythoncom.PumpWaitingMessages() # print 'pumping' else: break if ic.Running(): if time.time() - start_time > 5: print ic.Running() break # msgbox(0, "Measurement Started" + chr(13) + "Now CAPL is called", "Info", 16) # Another not elegant way ''' import win32event, time event = win32event.CreateEvent(None, 0, 0, None) timeStart = time.time() timeTic = timeStart while True: rc = win32event.MsgWaitForMultipleObjects((event, ), 0, done_time, win32event.QS_ALLEVENTS) if rc == win32event.WAIT_OBJECT_0: pass elif rc == win32event.WAIT_OBJECT_0 + 1: pythoncom.PumpWaitingMessages() elif rc == win32event.WAIT_TIMEOUT: print(' WaitMsg: got donetime') return True else: print('Unrecognized event') if time.time() - timeStart > timeout: print(' ##### got timeout') return False if time.time() - timeTic > 1: print('.', ) timeTic = time.time()
def pumpMessages(self): while True: res = win32event.MsgWaitForMultipleObjects((self.shutdownEvent,), 0, win32event.INFINITE, win32event.QS_ALLEVENTS) if res == win32event.WAIT_OBJECT_0: break elif res == win32event.WAIT_OBJECT_0 + 1: if pythoncom.PumpWaitingMessages(): break # wm_quit else: raise RuntimeError("unexpected win32wait return value")
def serve(clsid="{506e67c3-55b5-48c3-a035-eed5deea7d6d}"): """Launch the COM server, clsid is the XLPython object class id """ clsid = pywintypes.IID(clsid) # Ovveride CreateInstance in default policy to instantiate the XLPython object --- BaseDefaultPolicy = win32com.server.policy.DefaultPolicy class MyPolicy(BaseDefaultPolicy): def _CreateInstance_(self, reqClsid, reqIID): if reqClsid == clsid: return serverutil.wrap(XLPython(), reqIID) 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() print('xlwings server running, clsid=%s' % clsid) while True: rc = win32event.MsgWaitForMultipleObjects([idle_queue_event], 0, win32event.INFINITE, win32event.QS_ALLEVENTS) while True: pythoncom.PumpWaitingMessages() if not idle_queue: break task = idle_queue.pop(0) try: task() except: import traceback print("TaskQueue '%s' threw an exeception: %s", task, traceback.format_exc()) pythoncom.CoRevokeClassObject(revokeId) pythoncom.CoUninitialize()
def __wait_msg_pump(self, timeout=2000): # When user does mouseover it runs QS_SENDMESSAGE 0x0040 in a loop . . . # Also we receive ALL mouse clicks . . . rc = win32event.MsgWaitForMultipleObjects( (self.__event,), # list of objects 0, # wait all timeout, # timeout win32event.QS_ALLINPUT, # type of input ) if rc == win32event.WAIT_OBJECT_0+1: # Message waiting. if win32gui.PumpWaitingMessages(): # Received WM_QUIT, so return True. win32gui.PostMessage(self.__w32hid.hwnd, win32con.WM_QUIT, 0, 0) return True
def WaitWhileProcessingMessages(event, timeout=2): start = time.clock() while True: # Wake 4 times a second - we can't just specify the # full timeout here, as then it would reset for every # message we process. rc = win32event.MsgWaitForMultipleObjects((event, ), 0, 250, win32event.QS_ALLEVENTS) if rc == win32event.WAIT_OBJECT_0: # event signalled - stop now! return True if (time.clock() - start) > timeout: # Timeout expired. return False # must be a message. pythoncom.PumpWaitingMessages()
def serve(clsid="{506e67c3-55b5-48c3-a035-eed5deea7d6d}"): """Launch the COM server, clsid is the XLPython object class id """ clsid = pywintypes.IID(clsid) # Ovveride CreateInstance in default policy to instantiate the XLPython object --- BaseDefaultPolicy = win32com.server.policy.DefaultPolicy class MyPolicy(BaseDefaultPolicy): def _CreateInstance_(self, reqClsid, reqIID): if reqClsid == clsid: return serverutil.wrap(XLPython(), reqIID) 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() msg = 'xlwings server running, clsid=%s' logger.info(msg, clsid) if logger.hasHandlers() else print(msg % clsid) waitables = [idle_queue_event] while True: timeout = TIMEOUT if idle_queue else win32event.INFINITE rc = win32event.MsgWaitForMultipleObjects(waitables, 0, timeout, win32event.QS_ALLEVENTS) if rc == win32event.WAIT_OBJECT_0 or rc == win32event.WAIT_TIMEOUT: while idle_queue: task = idle_queue.popleft() if not _execute_task(task): break elif rc == win32event.WAIT_OBJECT_0 + len(waitables): if pythoncom.PumpWaitingMessages(): break # wm_quit pythoncom.CoRevokeClassObject(revokeId) pythoncom.CoUninitialize()
def serve(clsid="{506e67c3-55b5-48c3-a035-eed5deea7d6d}"): """Launch the COM server, clsid is the XLPython object class id""" clsid = pywintypes.IID(clsid) # Override CreateInstance in default policy to instantiate the XLPython object --- BaseDefaultPolicy = win32com.server.policy.DefaultPolicy class MyPolicy(BaseDefaultPolicy): def _CreateInstance_(self, reqClsid, reqIID): if reqClsid == clsid: return serverutil.wrap(XLPython(), reqIID) 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() if not loop.is_running(): t = threading.Thread(target=_start_background_loop, daemon=True) t.start() tid = t.ident else: tid = None msg = "xlwings server running, clsid=%s, event loop on %s" logger.info(msg, clsid, tid) if logger.hasHandlers() else print(msg % (clsid, tid)) while True: rc = win32event.MsgWaitForMultipleObjects( (), 0, win32event.INFINITE, win32event.QS_ALLEVENTS ) if rc == win32event.WAIT_OBJECT_0: if pythoncom.PumpWaitingMessages(): break # wm_quit pythoncom.CoRevokeClassObject(revokeId) pythoncom.CoUninitialize()
def main(): flags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME dh = win32file.CreateFile( "C:\\", 0x0001, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS | win32con.FILE_FLAG_OVERLAPPED, None) overlapped = pywintypes.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) buf = win32file.AllocateReadBuffer(8192) changes = [] iterations = 0 timedout = False while True: iterations += 1 print(iterations) if timedout == False: # This is to ensure the directory handle only has one instance of ReadDirectoryChangesW at a time. # If this isn't here and ReadDirectoryChangesW stacks up without being used, it will break after 60-64 iterations if # using a mapped network folder and the directory handle will need to be closed (dh.close()) and reopened. win32file.ReadDirectoryChangesW(dh, buf, True, flags, overlapped) rc = win32event.MsgWaitForMultipleObjects([overlapped.hEvent], False, 5000, win32event.QS_ALLEVENTS) # rc = win32event.WaitForSingleObject(overlapped.hEvent, 5000) # Also acceptable # rc = win32event.WaitForMultipleObjects([overlapped.hEvent], False, 5000) # Also acceptable if rc == win32event.WAIT_TIMEOUT: timedout = True print('timed out') if rc == win32event.WAIT_OBJECT_0: # can replace win32event.WAIT_OBJECT_0 with the integer 0 (and win32event.WAIT_OBJECT_0+1 with 1) timedout = False # since we got a result, reset the timedout variable so ReadDirectoryChangesW can be run again result = win32file.GetOverlappedResult(dh, overlapped, True) if result: bufferData = win32file.FILE_NOTIFY_INFORMATION(buf, result) changes.extend(bufferData) print(bufferData) for x in bufferData: if x[1] == 'break': # for testing, create a file named "break" in the watched folder and the script will stop and print the list of files print("\nFinal result!") return changes else: print('dir handle closed')
def start(self): #запуск сервера server = dde.CreateServer() server.AddTopic(QuikTopic(self)) server.Create(self.topic_name) event = win32event.CreateEvent(None, 0, 0, None) while 1: win32ui.PumpWaitingMessages(0, -1) rc = win32event.MsgWaitForMultipleObjects((event, ), 0, 100, win32event.QS_ALLEVENTS) if rc == win32event.WAIT_OBJECT_0: break #elif rc==win32event.WAIT_OBJECT_0+1: # print "OK1" #if win32ui.PumpWaitingMessages(0,-1): # raise RuntimeError("We got an unexpected WM_QUIT message!") elif rc == win32event.WAIT_TIMEOUT: pass
def start(self): if self.instance_running(): try: self.stop() except SystemExit: return win32gui.PostQuitMessage(0) # Load today's count data back from data file super(KeyCounter, self).start() self.hook_keyboard() self.create_window() self.update_tray_icon() while 1: try: win32event.MsgWaitForMultipleObjects([], 0, self.MSPF, win32event.QS_ALLEVENTS) win32gui.PumpWaitingMessages() except SystemExit: win32gui.PostQuitMessage(0)
def run(self): continueloop = True overlapped = self.plugin.serial._overlappedRead hComPort = self.plugin.serial.hComPort hEvent = overlapped.hEvent n = 1 waitingOnRead = False buf = win32file.AllocateReadBuffer(n) reply = {'suffix': None, 'payload': None} lastEvent = None while continueloop: if not waitingOnRead: win32event.ResetEvent(hEvent) hr, _ = win32file.ReadFile(hComPort, buf, overlapped) if hr == 997: waitingOnRead = True elif hr == 0: pass else: raise rc = win32event.MsgWaitForMultipleObjects( (hEvent, self.plugin.stopEvent), 0, 1000, win32event.QS_ALLINPUT) if rc == win32event.WAIT_OBJECT_0: n = win32file.GetOverlappedResult(hComPort, overlapped, 1) if n: reply = self.plugin.Decode(ord(buf)) if reply is not None and reply != lastEvent: self.plugin.TriggerEnduringEvent(**reply) lastEvent = reply.copy() waitingOnRead = False elif rc == win32event.WAIT_OBJECT_0 + 1: continueloop = False elif rc == win32event.WAIT_TIMEOUT: self.plugin.EndLastEvent() else: eg.PrintError("unknown message") eg.PrintNotice(str(rc))
def _MessagePump(): while 1: rc = win32event.MsgWaitForMultipleObjects( (StopEvent,OtherEvent), 0, # wait for all = false TIMEOUT, # (or win32event.INFINITE) win32event.QS_ALLEVENTS) # type of input # You can call a function here if it doesn't take too long. # It will get executed *at least* every 200ms -- possibly # a lot more, depending on the number of windows messages received. if rc == win32event.WAIT_OBJECT_0: # Our first event listed was triggered. # Someone wants us to exit. break elif rc == win32event.WAIT_OBJECT_0+1: # Our second event "OtherEvent" listed was set. # This is from some other component - # wait on as many events as you need elif rc == win32event.WAIT_OBJECT_0+2: # A windows message is waiting - take care of it. # (Don't ask me why a WAIT_OBJECT_MSG isn't defined < WAIT_OBJECT_0) # Note: this must be done for COM and other windowsy # things to work. if pythoncom.PumpWaitingMessages(): break # wm_quit elif rc == win32event.WAIT_TIMEOUT: # Our timeout has elapsed. # Do some work here (e.g, poll something can you can't thread) # or just feel good to be alive. # Good place to call watchdog(). (Editor's note: See my "thread lifetime" recepie.) pass else: raise RuntimeError( "unexpected win32wait return value")
def _MessagePump(): waitables = StopEvent, OtherEvent while True: rc = win32event.MsgWaitForMultipleObjects( waitables, 0, # Wait for all = false, so it waits for any one TIMEOUT, # (or win32event.INFINITE) win32event.QS_ALLEVENTS) # Accept all kinds of events # You can call a function here, if it doesn't take too long. It will # be executed at least every TIMEOUT ms -- possibly a lot more often, # depending on the number of Windows messages received. if rc == win32event.WAIT_OBJECT_0: # Our first event listed, the StopEvent, was triggered, so # we must exit, terminating the message pump break elif rc == win32event.WAIT_OBJECT_0 + 1: # Our second event listed, "OtherEvent", was set. Do # whatever needs to be done -- you can wait on as many # kernel-waitable objects as needed (events, locks, # processes, threads, notifications, and so on). pass elif rc == win32event.WAIT_OBJECT_0 + len(waitables): # A windows message is waiting - take care of it. (Don't # ask me why a WAIT_OBJECT_MSG isn't defined < # WAIT_OBJECT_0...!). # This message-serving MUST be done for COM, DDE, and other # Windows-y things to work properly! if pythoncom.PumpWaitingMessages(): break # we received a wm_quit message elif rc == win32event.WAIT_TIMEOUT: # Our timeout has elapsed. # Do some work here (e.g, poll something you can't thread) # or just feel good to be alive. pass else: raise RuntimeError("unexpected win32wait return value")
# Note to self: A domain that cannot be resolved will cause # TRANSIENT_ERROR instead of ERROR, and the JobError notification will # not be triggered! This can bite you during testing depending on how # your DNS is configured. For example, if you use OpenDNS.org's DNS # servers, an invalid hostname will *always* be resolved (they # redirect you to a search page), so be careful when testing. job.AddFile( "http://www.python.org/favicon.ico", os.path.join(tempfile.gettempdir(), "bits-favicon.ico"), ) job.AddFile( "http://www.python.org/missing-favicon.ico", os.path.join(tempfile.gettempdir(), "bits-missing-favicon.ico"), ) for f in job.EnumFiles(): print("Downloading", f.GetRemoteName()) print("To", f.GetLocalName()) job.Resume() while True: rc = win32event.MsgWaitForMultipleObjects((StopEvent, ), 0, TIMEOUT, win32event.QS_ALLEVENTS) if rc == win32event.WAIT_OBJECT_0: break elif rc == win32event.WAIT_OBJECT_0 + 1: if pythoncom.PumpWaitingMessages(): break # wm_quit
def testMsgWaitForMultipleObjects2(self): # test with non-empty list event = win32event.CreateEvent(None, 0, 0, None) res = win32event.MsgWaitForMultipleObjects([event], 0, 0, 0) self.assertEquals(res, win32event.WAIT_TIMEOUT)
def testMsgWaitForMultipleObjects(self): # this function used to segfault when called with an empty list res = win32event.MsgWaitForMultipleObjects([], 0, 0, 0) self.assertEquals(res, win32event.WAIT_TIMEOUT)