我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用win32event.SetEvent()。
def test_connect_without_payload(self): giveup_event = win32event.CreateEvent(None, 0, 0, None) t = threading.Thread(target=self.connect_thread_runner, args=(False, giveup_event)) t.start() time.sleep(0.1) s2 = socket.socket() ol = pywintypes.OVERLAPPED() s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand try: win32file.ConnectEx(s2, self.addr, ol) except win32file.error, exc: win32event.SetEvent(giveup_event) if exc.winerror == 10022: # WSAEINVAL raise TestSkipped("ConnectEx is not available on this platform") raise # some error error we don't expect. win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() buff = win32file.AllocateReadBuffer(1024) win32file.WSARecv(s2, buff, ol, 0) length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] self.assertEqual(self.response, str2bytes('some expected response')) t.join(5) self.failIf(t.isAlive(), "worker thread didn't terminate")
def test_connect_without_payload(self): giveup_event = win32event.CreateEvent(None, 0, 0, None) t = threading.Thread(target=self.connect_thread_runner, args=(False, giveup_event)) t.start() time.sleep(0.1) s2 = socket.socket() ol = pywintypes.OVERLAPPED() s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand try: win32file.ConnectEx(s2, self.addr, ol) except win32file.error as exc: win32event.SetEvent(giveup_event) if exc.winerror == 10022: # WSAEINVAL raise TestSkipped("ConnectEx is not available on this platform") raise # some error error we don't expect. win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() buff = win32file.AllocateReadBuffer(1024) win32file.WSARecv(s2, buff, ol, 0) length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] self.assertEqual(self.response, str2bytes('some expected response')) t.join(5) self.failIf(t.isAlive(), "worker thread didn't terminate")
def test_addEvent(self): """ When an event which has been added to the reactor is set, the action associated with the event is invoked in the reactor thread. """ reactorThreadID = getThreadID() reactor = self.buildReactor() event = win32event.CreateEvent(None, False, False, None) finished = Deferred() finished.addCallback(lambda ignored: reactor.stop()) listener = Listener(finished) reactor.addEvent(event, listener, 'occurred') reactor.callWhenRunning(win32event.SetEvent, event) self.runReactor(reactor) self.assertTrue(listener.success) self.assertEqual(reactorThreadID, listener.logThreadID) self.assertEqual(reactorThreadID, listener.eventThreadID)
def test_ioThreadDoesNotChange(self): """ Using L{IReactorWin32Events.addEvent} does not change which thread is reported as the I/O thread. """ results = [] def check(ignored): results.append(isInIOThread()) reactor.stop() reactor = self.buildReactor() event = win32event.CreateEvent(None, False, False, None) finished = Deferred() listener = Listener(finished) finished.addCallback(check) reactor.addEvent(event, listener, 'occurred') reactor.callWhenRunning(win32event.SetEvent, event) self.runReactor(reactor) self.assertTrue(listener.success) self.assertEqual([True], results)
def test_disconnectedOnError(self): """ If the event handler raises an exception, the event is removed from the reactor and the handler's C{connectionLost} method is called in the I/O thread and the exception is logged. """ reactorThreadID = getThreadID() reactor = self.buildReactor() event = win32event.CreateEvent(None, False, False, None) result = [] finished = Deferred() finished.addBoth(result.append) finished.addBoth(lambda ignored: reactor.stop()) listener = Listener(finished) reactor.addEvent(event, listener, 'brokenOccurred') reactor.callWhenRunning(win32event.SetEvent, event) self.runReactor(reactor) self.assertIsInstance(result[0], Failure) result[0].trap(RuntimeError) self.assertEqual(reactorThreadID, listener.connLostThreadID) self.assertEqual(1, len(self.flushLoggedErrors(RuntimeError)))
def test_disconnectOnReturnValue(self): """ If the event handler returns a value, the event is removed from the reactor and the handler's C{connectionLost} method is called in the I/O thread. """ reactorThreadID = getThreadID() reactor = self.buildReactor() event = win32event.CreateEvent(None, False, False, None) result = [] finished = Deferred() finished.addBoth(result.append) finished.addBoth(lambda ignored: reactor.stop()) listener = Listener(finished) reactor.addEvent(event, listener, 'returnValueOccurred') reactor.callWhenRunning(win32event.SetEvent, event) self.runReactor(reactor) self.assertIsInstance(result[0], Failure) result[0].trap(EnvironmentError) self.assertEqual(reactorThreadID, listener.connLostThreadID)
def registerHandler(self, signum, handler): """Register a handler function that will be called when the process recieves the signal signum. The signum argument must be a signal constant such as SIGTERM. The handler argument must be a function or method that takes no arguments.""" items = self.registry.get(signum) if items is None: items = self.registry[signum] = [] # Create an event for this signal. event_name = event_name_prefix + str(signum) sa = createEventSecurityObject() hevent = win32event.CreateEvent(sa, 0, 0, event_name) self.event_handles[signum] = hevent # Let the worker thread know there is a new handle. win32event.SetEvent(self.admin_event_handle) signame = get_signal_name(signum) logger.debug( "Installed sighandler for %s (%s)" % (signame, event_name)) items.insert(0, handler)
def pipe(bufsize=8192): """Creates overlapped (asynchronous) pipe. """ name = r'\\.\pipe\pycos-pipe-%d-%d' % (os.getpid(), next(_pipe_id)) openmode = (win32pipe.PIPE_ACCESS_INBOUND | win32file.FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE) pipemode = (win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE) rh = wh = None try: rh = win32pipe.CreateNamedPipe( name, openmode, pipemode, 1, bufsize, bufsize, win32pipe.NMPWAIT_USE_DEFAULT_WAIT, None) wh = win32file.CreateFile( name, win32file.GENERIC_WRITE | winnt.FILE_READ_ATTRIBUTES, 0, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_OVERLAPPED, None) overlapped = pywintypes.OVERLAPPED() # 'yield' can't be used in constructor so use sync wait # (in this case it is should be okay) overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) rc = win32pipe.ConnectNamedPipe(rh, overlapped) if rc == winerror.ERROR_PIPE_CONNECTED: win32event.SetEvent(overlapped.hEvent) rc = win32event.WaitForSingleObject(overlapped.hEvent, 1000) overlapped = None if rc != win32event.WAIT_OBJECT_0: pycos.logger.warning('connect failed: %s' % rc) raise Exception(rc) return (rh, wh) except: if rh is not None: win32file.CloseHandle(rh) if wh is not None: win32file.CloseHandle(wh) raise
def SvcStop(self): self.netkeeper.disconnect() self.logger.info("service is stop....") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.run = False
def _testInterpInThread(self, stopEvent, interp): try: self._doTestInThread(interp) finally: win32event.SetEvent(stopEvent)
def TestInterpInThread(stopEvent, cookie): try: DoTestInterpInThread(cookie) finally: win32event.SetEvent(stopEvent)
def OnDocumentComplete(self, pDisp=pythoncom.Empty, URL=pythoncom.Empty): thread = win32api.GetCurrentThreadId() print "OnDocumentComplete event processed on thread %d"%thread # Set the event our main thread is waiting on. win32event.SetEvent(self.event)
def OnQuit(self): thread = win32api.GetCurrentThreadId() print "OnQuit event processed on thread %d"%thread win32event.SetEvent(self.event)
def OnDocumentComplete(self, pDisp=pythoncom.Empty, URL=pythoncom.Empty): # # Caution: Since the main thread and events thread(s) are different # it may be necessary to serialize access to shared data. Because # this is a simple test case, that is not required here. Your # situation may be different. Caveat programmer. # thread = win32api.GetCurrentThreadId() print "OnDocumentComplete event processed on thread %d"%thread # Set the event our main thread is waiting on. win32event.SetEvent(self.event)
def pacemaker(self, timeout=60): # This is a stand-alone heartbeat generator. To pulse from your own control loop, # call your AbstractLog subclass instance event handler (e.g. AbstractLog['event']() def __target(timeout=60): if platform.uname()[0].lower() == "windows": import win32con import win32event self.running = True kill = win32event.CreateEvent(None, 1, 0, None) pulse = win32event.CreateWaitableTimer(None, 0, None) win32event.SetWaitableTimer(pulse, 0, timeout*1000, None, None, False) while(self.running): try: result = win32event.WaitForMultipleObjects([kill, pulse], False, 1000) # if kill signal received, break loop if(result == win32con.WAIT_OBJECT_0): break # elif timeout has passed, generate a pulse elif(result == win32con.WAIT_OBJECT_0 + 1): self['event']() except: self.notifyOfError("Pacemaker shutdown. Heartbeats will not be generated.") win32event.SetEvent(kill) elif self.options['Verbose']: print "Pacemaker only supported in Windows at this time. " try: self.thread = threading.Thread(target=__target, args=(timeout,) ) self.thread.start() except: self.notifyOfError("Pacemaker thread exception. Heartbeats will not be generated.")
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.log('stopping') self.stop() self.log('stopped') win32event.SetEvent(self.stop_event) self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop)
def SvcStop(self): try: print("Stopping...") servicemanager.LogInfoMsg("Stopping...") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.isAlive = False except Exception as e: print("Error: " + str(e)) servicemanager.LogErrorMsg("Error: " + str(e))
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) _exit_status = of.broker.broker.stop_broker("Shutting down the Broker service") self.ReportServiceStatus(win32service.SERVICE_STOPPED) os.exit(_exit_status)
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.stop_event) self.stop_requested = True # Send the http request to shutdown the server try: urllib2.urlopen('http://localhost:80/shutdown') except Exception: urllib2.urlopen('http://localhost:5000/shutdown')
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.stop_event) logging.info('Stopping ShakeCast Server...') self.stop_requested = True ui = UI() ui.send('shutdown')
def JobTransferred(self, job): print 'Job Transferred', job job.Complete() win32event.SetEvent(StopEvent) # exit msg pump
def increment (self, id, time): print 'x = %d' % self.x self.x = self.x + 1 # if we've reached the max count, # kill off the timer. if self.x > self.max: # we could have used 'self.id' here, too timer.kill_timer (id) win32event.SetEvent(self.event) # create a counter that will count from '1' thru '10', incrementing # once a second, and then stop.
def Callback( hras, msg, state, error, exterror): # print "Callback called with ", hras, msg, state, error, exterror stateName = stateMap.get(state, "Unknown state?") print "Status is %s (%04lx), error code is %d" % (stateName, state, error) finished = state in [win32ras.RASCS_Connected] if finished: win32event.SetEvent(callbackEvent) if error != 0 or int( state ) == win32ras.RASCS_Disconnected: # we know for sure this is a good place to hangup.... print "Detected call failure: %s" % win32ras.GetErrorString( error ) HangUp( hras ) win32event.SetEvent(callbackEvent)
def testSetEvent(self): event = win32event.CreateEvent(None, True, False, None) self.assertNotSignaled(event) res = win32event.SetEvent(event) self.assertEquals(res, None) self.assertSignaled(event) event.close() self.assertRaises(pywintypes.error, win32event.SetEvent, event)
def _DocumentStateChanged(self): win32event.SetEvent(self.adminEvent)
def SignalStop(self): win32event.SetEvent(self.stopEvent)
def _StopThread(self): win32event.SetEvent(self.hStopThread) self.hStopThread = None
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.isAlive = False
def JobTransferred(self, job): print('Job Transferred', job) job.Complete() win32event.SetEvent(StopEvent) # exit msg pump
def increment (self, id, time): print('x = %d' % self.x) self.x = self.x + 1 # if we've reached the max count, # kill off the timer. if self.x > self.max: # we could have used 'self.id' here, too timer.kill_timer (id) win32event.SetEvent(self.event) # create a counter that will count from '1' thru '10', incrementing # once a second, and then stop.
def test_connect_with_payload(self): giveup_event = win32event.CreateEvent(None, 0, 0, None) t = threading.Thread(target=self.connect_thread_runner, args=(True, giveup_event)) t.start() time.sleep(0.1) s2 = socket.socket() ol = pywintypes.OVERLAPPED() s2.bind(('0.0.0.0', 0)) # connectex requires the socket be bound beforehand try: win32file.ConnectEx(s2, self.addr, ol, str2bytes("some expected request")) except win32file.error as exc: win32event.SetEvent(giveup_event) if exc.winerror == 10022: # WSAEINVAL raise TestSkipped("ConnectEx is not available on this platform") raise # some error error we don't expect. win32file.GetOverlappedResult(s2.fileno(), ol, 1) ol = pywintypes.OVERLAPPED() buff = win32file.AllocateReadBuffer(1024) win32file.WSARecv(s2, buff, ol, 0) length = win32file.GetOverlappedResult(s2.fileno(), ol, 1) self.response = buff[:length] self.assertEqual(self.response, str2bytes('some expected response')) self.assertEqual(self.request, str2bytes('some expected request')) t.join(5) self.failIf(t.isAlive(), "worker thread didn't terminate")