我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用win32event.CreateEvent()。
def BeginThreadsSimpleMarshal(self, numThreads): """Creates multiple threads using simple (but slower) marshalling. Single interpreter object, but a new stream is created per thread. Returns the handles the threads will set when complete. """ interp = win32com.client.Dispatch("Python.Interpreter") events = [] threads = [] for i in range(numThreads): hEvent = win32event.CreateEvent(None, 0, 0, None) events.append(hEvent) interpStream = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, interp._oleobj_) t = threading.Thread(target=self._testInterpInThread, args=(hEvent, interpStream)) t.setDaemon(1) # so errors dont cause shutdown hang t.start() threads.append(t) interp = None return threads, events # # NOTE - this doesnt quite work - Im not even sure it should, but Greg reckons # you should be able to avoid the marshal per thread! # I think that refers to CoMarshalInterface though...
def BeginThreadsFastMarshal(self, numThreads): """Creates multiple threads using fast (but complex) marshalling. The marshal stream is created once, and each thread uses the same stream Returns the handles the threads will set when complete. """ interp = win32com.client.Dispatch("Python.Interpreter") if freeThreaded: interp = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, interp._oleobj_) events = [] threads = [] for i in range(numThreads): hEvent = win32event.CreateEvent(None, 0, 0, None) t = threading.Thread(target=self._testInterpInThread, args=(hEvent, interp)) t.setDaemon(1) # so errors dont cause shutdown hang t.start() events.append(hEvent) threads.append(t) return threads, events
def testNotifyChange(self): def change(): hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name) try: win32api.RegSetValue(hkey, None, win32con.REG_SZ, "foo") finally: win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name) evt = win32event.CreateEvent(None,0,0,None) ## REG_NOTIFY_CHANGE_LAST_SET - values ## REG_CHANGE_NOTIFY_NAME - keys ## REG_NOTIFY_CHANGE_SECURITY - security descriptor ## REG_NOTIFY_CHANGE_ATTRIBUTES win32api.RegNotifyChangeKeyValue(win32con.HKEY_CURRENT_USER,1,win32api.REG_NOTIFY_CHANGE_LAST_SET,evt,True) ret_code=win32event.WaitForSingleObject(evt,0) # Should be no change. self.failUnless(ret_code==win32con.WAIT_TIMEOUT) change() # Our event should now be in a signalled state. ret_code=win32event.WaitForSingleObject(evt,0) self.failUnless(ret_code==win32con.WAIT_OBJECT_0)
def testCleanup1(self): # We used to clobber all outstanding exceptions. def f1(invalidate): import win32event h = win32event.CreateEvent(None, 0, 0, None) if invalidate: win32api.CloseHandle(int(h)) 1/0 # If we invalidated, then the object destruction code will attempt # to close an invalid handle. We don't wan't an exception in # this case def f2(invalidate): """ This function should throw an IOError. """ try: f1(invalidate) except ZeroDivisionError, exc: raise IOError("raise 2") self.assertRaises(IOError, f2, False) # Now do it again, but so the auto object destruction # actually fails. self.assertRaises(IOError, f2, True)
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_basics(self): s = socket.socket() e = win32event.CreateEvent(None, 1, 0, None) win32file.WSAEventSelect(s, e, 0) self.assertEquals(win32file.WSAEnumNetworkEvents(s), {}) self.assertEquals(win32file.WSAEnumNetworkEvents(s, e), {}) self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, s, e, 3) self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, s, "spam") self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, "spam", e) self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, "spam") f = open("NUL") h = win32file._get_osfhandle(f.fileno()) self.assertRaises(win32file.error, win32file.WSAEnumNetworkEvents, h) self.assertRaises(win32file.error, win32file.WSAEnumNetworkEvents, s, h) try: win32file.WSAEnumNetworkEvents(h) except win32file.error, e: self.assertEquals(e.winerror, win32file.WSAENOTSOCK) try: win32file.WSAEnumNetworkEvents(s, h) except win32file.error, e: # According to the docs it would seem reasonable that # this would fail with WSAEINVAL, but it doesn't. self.assertEquals(e.winerror, win32file.WSAENOTSOCK)
def testCleanup1(self): # We used to clobber all outstanding exceptions. def f1(invalidate): import win32event h = win32event.CreateEvent(None, 0, 0, None) if invalidate: win32api.CloseHandle(int(h)) 1/0 # If we invalidated, then the object destruction code will attempt # to close an invalid handle. We don't wan't an exception in # this case def f2(invalidate): """ This function should throw an IOError. """ try: f1(invalidate) except ZeroDivisionError as exc: raise IOError("raise 2") self.assertRaises(IOError, f2, False) # Now do it again, but so the auto object destruction # actually fails. self.assertRaises(IOError, f2, True)
def test_basics(self): s = socket.socket() e = win32event.CreateEvent(None, 1, 0, None) win32file.WSAEventSelect(s, e, 0) self.assertEquals(win32file.WSAEnumNetworkEvents(s), {}) self.assertEquals(win32file.WSAEnumNetworkEvents(s, e), {}) self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, s, e, 3) self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, s, "spam") self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, "spam", e) self.assertRaises(TypeError, win32file.WSAEnumNetworkEvents, "spam") f = open("NUL") h = win32file._get_osfhandle(f.fileno()) self.assertRaises(win32file.error, win32file.WSAEnumNetworkEvents, h) self.assertRaises(win32file.error, win32file.WSAEnumNetworkEvents, s, h) try: win32file.WSAEnumNetworkEvents(h) except win32file.error as e: self.assertEquals(e.winerror, win32file.WSAENOTSOCK) try: win32file.WSAEnumNetworkEvents(s, h) except win32file.error as e: # According to the docs it would seem reasonable that # this would fail with WSAEINVAL, but it doesn't. self.assertEquals(e.winerror, win32file.WSAENOTSOCK)
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 instance_running(self): ''' Use CreateEvent to make sure there is only one instance running ''' if self.SICHECK_EVENT is None: self.SICHECK_EVENT = win32event.CreateEvent( None, 1, 0, self.GUID ) # An instance is already running, quit if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS: win32gui.MessageBox( self.HWND, 'You can only run one instance at a time', 'Seems like KeyCounter is already running', win32con.MB_OK ) return self.stop()
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 __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.logger = logger self.run = True
def notifyOnExit(self, processHandle, processTransport): processHandleKey = self.phandleToPhandleKey[processHandle] # If there are available threads, use one of them if len(self.availableThreads) > 0: wfmoThread = self.availableThreads[0] self.threadToNumProcessHandles[wfmoThread] += 1 self.phandleKeyToThreadHandle[processHandleKey] = wfmoThread # Update used/available thread lists if self.threadToNumProcessHandles[wfmoThread] == 63: self.usedThreads.append(wfmoThread) self.availableThreads.remove(wfmoThread) # Make sure the message window has been created so # we can send messages to the thread. if self.threadToMsgWindowCreated[wfmoThread] is False: val = WaitForSingleObject(self.threadToMsgWindowCreationEvent[wfmoThread], INFINITE) if val != WAIT_OBJECT_0: raise RuntimeError("WaitForSingleObject returned %d. It should only return %d" % (val, WAIT_OBJECT_0)) # Notify the thread that it should wait on the process handle. if win32api.PostMessage( self.threadToMsgWindow[wfmoThread], WM_NEW_PHANDLE, # message processHandleKey, # wParam 0 # lParam ) == 0: raise Exception("Failed to post thread message!") else: # Create a new thread and wait on the proc handle wfmoThread = threading.Thread( target=self.doWaitForProcessExit, args=(processHandleKey,), name="iocpreactor.process_waiter.ProcessWaiter.waitForProcessExit pid=%d" % self.realPid) # Create a window creation event that will be triggered from the thread self.threadToMsgWindowCreationEvent[wfmoThread] = CreateEvent(None, 0, 0, None) self.threadToMsgWindowCreated[wfmoThread] = False self.threadToNumProcessHandles[wfmoThread] = 1 self.availableThreads.append(wfmoThread) self.phandleKeyToThreadHandle[processHandleKey] = wfmoThread wfmoThread.start()
def __init__(self, protocol, deviceNameOrPortNumber, reactor, baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE, stopbits = STOPBITS_ONE, xonxoff = 0, rtscts = 0): self._serial = serial.Serial(deviceNameOrPortNumber, baudrate=baudrate, bytesize=bytesize, parity=parity, stopbits=stopbits, timeout=None, xonxoff=xonxoff, rtscts=rtscts) self.flushInput() self.flushOutput() self.reactor = reactor self.protocol = protocol self.outQueue = [] self.closed = 0 self.closedNotifies = 0 self.writeInProgress = 0 self.protocol = protocol self._overlappedRead = win32file.OVERLAPPED() self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None) self._overlappedWrite = win32file.OVERLAPPED() self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None) self.reactor.addEvent(self._overlappedRead.hEvent, self, 'serialReadEvent') self.reactor.addEvent(self._overlappedWrite.hEvent, self, 'serialWriteEvent') self.protocol.makeConnection(self) flags, comstat = win32file.ClearCommError(self._serial.hComPort) rc, self.read_buf = win32file.ReadFile(self._serial.hComPort, win32file.AllocateReadBuffer(1), self._overlappedRead)
def BeginThreadsSimpleMarshal(numThreads, cookie): """Creates multiple threads using simple (but slower) marshalling. Single interpreter object, but a new stream is created per thread. Returns the handles the threads will set when complete. """ ret = [] for i in range(numThreads): hEvent = win32event.CreateEvent(None, 0, 0, None) thread.start_new(TestInterpInThread, (hEvent, cookie)) ret.append(hEvent) return ret
def __init__(self): self.event = win32event.CreateEvent(None, 0, 0, None)
def __init__(self): # We reuse this event for all events. self.event = win32event.CreateEvent(None, 0, 0, None)
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 __init__(self, *args): win32serviceutil.ServiceFramework.__init__(self, *args) self.log('init') self.stop_event = win32event.CreateEvent(None, 0, 0, None)
def __init__(self, args): # The exe-file has messages for the Event Log Viewer. # Register the exe-file as event source. # # Probably it would be better if this is done at installation time, # so that it also could be removed if the service is uninstalled. # Unfortunately it cannot be done in the 'if __name__ == "__main__"' # block below, because the 'frozen' exe-file does not run this code. # win32evtlogutil.AddSourceToRegistry(self._svc_display_name_, servicemanager.__file__, "Application") win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.WAIT_TIME = 1000 # in milliseconds
def __init__(self, args): try: win32serviceutil.ServiceFramework.__init__(self,args) servicemanager.LogInfoMsg("Logging to: " + log_location) print("Initialising...") servicemanager.LogInfoMsg("Initialising...") self.hWaitStop = win32event.CreateEvent(None,0,0,None) self.isAlive = True except Exception as e: print("Error: " + str(e)) servicemanager.LogErrorMsg("Error: " + str(e))
def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.stop_event = win32event.CreateEvent(None, 0, 0, None) self.stop_requested = False
def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60)
def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.stop_event = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) self.stop_requested = False
def connect_pipe(pipe, pipeName): overLap = pywintypes.OVERLAPPED() overLap.hEvent = win32event.CreateEvent(None, 1, 0, None) if overLap.hEvent == 0: raise PipeError('Could not create hEvent') try: # Wait for a pipe client connection ret = win32pipe.ConnectNamedPipe(pipe, overLap) if not ret in (0, ERROR_PIPE_CONNECTED): if ret == ERROR_IO_PENDING: ret = win32event.WaitForSingleObject(overLap.hEvent, 1000 * CONNECT_TIMEOUT_SECS) if ret != win32event.WAIT_OBJECT_0: # Timeout error raise PipeError('Timeout error') else: # API error raise PipeError('API error') ret = win32pipe.GetOverlappedResult(pipe, overLap, True) if not ret in (0, ERROR_PIPE_CONNECTED): # API Error raise PipeError('API error 2') except PipeError: # Named pipe exception win32file.CancelIo(pipe) pipe.close() raise except BaseException, err: win32file.CancelIo(pipe) pipe.close() pipe = None raise PipeError('BaseException : ' + str(err)) return pipe
def testRecord(self): d = ds.DirectSoundCaptureCreate(None, None) sdesc = ds.DSCBUFFERDESC() sdesc.dwBufferBytes = 352800 # 2 seconds sdesc.lpwfxFormat = pywintypes.WAVEFORMATEX() sdesc.lpwfxFormat.wFormatTag = pywintypes.WAVE_FORMAT_PCM sdesc.lpwfxFormat.nChannels = 2 sdesc.lpwfxFormat.nSamplesPerSec = 44100 sdesc.lpwfxFormat.nAvgBytesPerSec = 176400 sdesc.lpwfxFormat.nBlockAlign = 4 sdesc.lpwfxFormat.wBitsPerSample = 16 buffer = d.CreateCaptureBuffer(sdesc) event = win32event.CreateEvent(None, 0, 0, None) notify = buffer.QueryInterface(ds.IID_IDirectSoundNotify) notify.SetNotificationPositions((ds.DSBPN_OFFSETSTOP, event)) buffer.Start(0) win32event.WaitForSingleObject(event, -1) event.Close() data = buffer.Update(0, 352800) fname=os.path.join(win32api.GetTempPath(), 'test_directsound_record.wav') f = open(fname, 'wb') f.write(wav_header_pack(sdesc.lpwfxFormat, 352800)) f.write(data) f.close()
def __init__ (self, delay=1000, max=10): self.x = 0 self.max = max self.id = timer.set_timer (delay, self.increment) # Could use the threading module, but this is # a win32 extension test after all! :-) self.event = win32event.CreateEvent(None, 0, 0, None)
def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) # register for a device notification - we pass our service handle # instead of a window handle. filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE( GUID_DEVINTERFACE_USB_DEVICE) self.hdn = win32gui.RegisterDeviceNotification(self.ssh, filter, win32con.DEVICE_NOTIFY_SERVICE_HANDLE) # Override the base class so we can accept additional events.
def testMsgWaitForMultipleObjectsEx2(self): # test with non-empty list event = win32event.CreateEvent(None, 0, 0, None) res = win32event.MsgWaitForMultipleObjectsEx([event], 0, 0, 0) self.assertEquals(res, win32event.WAIT_TIMEOUT)
def testCreateEvent(self): event = win32event.CreateEvent(None, False, False, None) self.assertNotSignaled(event) event = win32event.CreateEvent(None, False, True, None) self.assertSignaled(event) self.assertNotSignaled(event) event = win32event.CreateEvent(None, True, True, None) self.assertSignaled(event) self.assertSignaled(event)
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 testResetEvent(self): event = win32event.CreateEvent(None, True, True, None) self.assertSignaled(event) res = win32event.ResetEvent(event) self.assertEquals(res, None) self.assertNotSignaled(event) event.close() self.assertRaises(pywintypes.error, win32event.ResetEvent, event)