我们从Python开源项目中,提取了以下38个代码示例,用于说明如何使用win32event.INFINITE。
def execute (cmd, timeout = 0): if timeout == 0: timeout = win32event.INFINITE info = win32process.CreateProcess(None, cmd, None, None, 0, 0, None, None, win32process.STARTUPINFO()) subprocess = info [0] rc = win32event.WaitForSingleObject (subprocess, timeout) if rc == win32event.WAIT_FAILED: return -1 if rc == win32event.WAIT_TIMEOUT: try: win32process.TerminateProcess (subprocess, 0) except pywintypes.error: return -3 return -2 if rc == win32event.WAIT_OBJECT_0: return win32process.GetExitCodeProcess(subprocess)
def timeout_execute (cmd, timeout = 0): if timeout == 0: timeout = win32event.INFINITE info = win32process.CreateProcess(None, cmd, None, None, 0, 0, None, None, win32process.STARTUPINFO()) subprocess = info [0] rc = win32event.WaitForSingleObject (subprocess, timeout) if rc == win32event.WAIT_FAILED: return -1 if rc == win32event.WAIT_TIMEOUT: try: win32process.TerminateProcess (subprocess, 0) except pywintypes.error: return -3 return -2 if rc == win32event.WAIT_OBJECT_0: return win32process.GetExitCodeProcess(subprocess)
def run(self): last_time = os.stat(self.filename)[stat.ST_MTIME] while 1: try: rc = win32event.WaitForSingleObject(self.handle, win32event.INFINITE) win32file.FindNextChangeNotification(self.handle) except win32event.error, details: # handle closed - thread should terminate. if details.winerror != winerror.ERROR_INVALID_HANDLE: raise break this_time = os.stat(self.filename)[stat.ST_MTIME] if this_time != last_time: print "Detected file change - flagging for reload." self.change_detected = True last_time = this_time
def Run(self): while 1: handles = [self.stopEvent, self.adminEvent] if self.watchEvent is not None: handles.append(self.watchEvent) rc = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: break elif rc == win32event.WAIT_OBJECT_0+1: self.RefreshEvent() else: win32api.PostMessage(self.hwnd, MSG_CHECK_EXTERNAL_FILE, 0, 0) try: # If the directory has been removed underneath us, we get this error. win32api.FindNextChangeNotification(self.watchEvent) except win32api.error, exc: print "Can not watch file", self.doc.GetPathName(), "for changes -", exc.strerror break # close a circular reference self.doc = None if self.watchEvent: win32api.FindCloseChangeNotification(self.watchEvent)
def CollectorThread(stopEvent, file): win32trace.InitRead() handle = win32trace.GetHandle() # Run this thread at a lower priority to the main message-loop (and printing output) # thread can keep up import win32process win32process.SetThreadPriority(win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_BELOW_NORMAL) try: while 1: rc = win32event.WaitForMultipleObjects((handle, stopEvent), 0, win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: # About the only char we can't live with is \0! file.write(win32trace.read().replace("\0", "<null>")) else: # Stop event break finally: win32trace.TermRead() print "Thread dieing"
def run(self): last_time = os.stat(self.filename)[stat.ST_MTIME] while 1: try: rc = win32event.WaitForSingleObject(self.handle, win32event.INFINITE) win32file.FindNextChangeNotification(self.handle) except win32event.error as details: # handle closed - thread should terminate. if details.winerror != winerror.ERROR_INVALID_HANDLE: raise break this_time = os.stat(self.filename)[stat.ST_MTIME] if this_time != last_time: print("Detected file change - flagging for reload.") self.change_detected = True last_time = this_time
def Run(self): while 1: handles = [self.stopEvent, self.adminEvent] if self.watchEvent is not None: handles.append(self.watchEvent) rc = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: break elif rc == win32event.WAIT_OBJECT_0+1: self.RefreshEvent() else: win32api.PostMessage(self.hwnd, MSG_CHECK_EXTERNAL_FILE, 0, 0) try: # If the directory has been removed underneath us, we get this error. win32api.FindNextChangeNotification(self.watchEvent) except win32api.error as exc: print("Can not watch file", self.doc.GetPathName(), "for changes -", exc.strerror) break # close a circular reference self.doc = None if self.watchEvent: win32api.FindCloseChangeNotification(self.watchEvent)
def CollectorThread(stopEvent, file): win32trace.InitRead() handle = win32trace.GetHandle() # Run this thread at a lower priority to the main message-loop (and printing output) # thread can keep up import win32process win32process.SetThreadPriority(win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_BELOW_NORMAL) try: while 1: rc = win32event.WaitForMultipleObjects((handle, stopEvent), 0, win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: # About the only char we can't live with is \0! file.write(win32trace.read().replace("\0", "<null>")) else: # Stop event break finally: win32trace.TermRead() print("Thread dieing")
def wait(self, state, interval=0.1, channel=None): """Wait for the given state(s), KeyboardInterrupt or SystemExit. Since this class uses native win32event objects, the interval argument is ignored. """ if isinstance(state, (tuple, list)): # Don't wait for an event that beat us to the punch ;) if self.state not in state: events = tuple([self._get_state_event(s) for s in state]) win32event.WaitForMultipleObjects( events, 0, win32event.INFINITE) else: # Don't wait for an event that beat us to the punch ;) if self.state != state: event = self._get_state_event(state) win32event.WaitForSingleObject(event, win32event.INFINITE)
def close(self): if self.file: self.file.close() self.file = None if sys.platform == "win32": win32event.WaitForMultipleObjects(self.wait_for, 1, win32event.INFINITE) return win32process.GetExitCodeProcess(self.child_pid) else: if self.thread: self.thread.join() if type(self.child_pid) == type([]): for pid in self.child_pid: exit = os.waitpid(pid, 0)[1] return exit else: return os.waitpid(self.child_pid, 0)[1] return None
def signalCheckerThread(self): while not self.shutdown_requested: handles = [self.admin_event_handle] signums = [None] for signum, handle in self.event_handles.items(): signums.append(signum) handles.append(handle) rc = win32event.WaitForMultipleObjects(handles, False, win32event.INFINITE) logger.debug("signalCheckerThread awake with %s" % rc) signum = signums[rc - win32event.WAIT_OBJECT_0] if signum is None: # Admin event - either shutdown, or new event object created. pass else: logger.debug("signalCheckerThread calling %s" % signum) self.signalHandler(signum, None) logger.debug("signalCheckerThread back") logger.debug("signalCheckerThread stopped")
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 processEnded(self, processHandle, processHandleKey): wfmoThread = self.phandleKeyToThreadHandle[processHandleKey] processTransport = self.phandleToTransport[processHandle] self.threadToNumEnded[wfmoThread] += 1 # Decrement proc handle count for thread self.threadToNumProcessHandles[wfmoThread] -= 1 # If we go from 63 to 62 phandles for the thread, mark it available. if self.threadToNumProcessHandles[wfmoThread] == 62: self.availableThreads.append(wfmoThread) self.usedThreads.remove(wfmoThread) # If we go to 0 phandles, end the thread elif self.threadToNumProcessHandles[wfmoThread] == 0: # Mark thread as unavailable self.availableThreads.remove(wfmoThread) # Notify the thread that it should exit. if not self.threadToMsgWindowCreated[wfmoThread]: 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. win32api.PostMessage( self.threadToMsgWindow[wfmoThread], # thread id WM_CLOSE_THREAD, # message 0, # wParam 0 # lParam ) # Cleanup thread resources del self.threadToNumProcessHandles[wfmoThread] del self.threadToMsgWindowCreated[wfmoThread] #del self.wfmoThread # Cleanup process handle resources del self.needWaiting[processHandleKey] del self.phandleToTransport[processHandle] # Call the transport's processEnded method processTransport.processEnded()
def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) try: self.ReportServiceStatus(win32service.SERVICE_RUNNING) self.log('start') self.start() self.log('wait') win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE) self.log('done') except Exception, x: self.log('Exception : %s' % x) self.SvcStop()
def wait(self, timeout=None): """Wait until the child exits. If timeout is not specified this blocks indefinately. Otherwise, timeout specifies the number of seconds to wait.""" if self.exitstatus is not None: return if timeout is None: timeout = INFINITE else: timeout = 1000 * timeout ret = WaitForSingleObject(self.child_handle, timeout) if ret == WAIT_TIMEOUT: raise TIMEOUT, 'Timeout exceeded in wait().' self.exitstatus = GetExitCodeProcess(self.child_handle) return self.exitstatus
def acquire(self): win32event.WaitForSingleObject(self.handle, win32event.INFINITE) self.locked = True
def wait(self, mSec=None): """ Wait for process to finish or for specified number of milliseconds to elapse. """ if mSec is None: mSec = win32event.INFINITE return win32event.WaitForSingleObject(self.hProcess, mSec)
def SvcDoRun(self): # do nothing at all - just wait to be stopped win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) # Write a stop message. servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, '') )
def join(self): win32event.WaitForSingleObject(self.processHandle, win32event.INFINITE) self.exitCode = win32process.GetExitCodeProcess(self.processHandle)
def testSimpleOverlapped(self): # Create a file in the %TEMP% directory. import win32event testName = os.path.join( win32api.GetTempPath(), "win32filetest.dat" ) desiredAccess = win32file.GENERIC_WRITE overlapped = pywintypes.OVERLAPPED() evt = win32event.CreateEvent(None, 0, 0, None) overlapped.hEvent = evt # Create the file and write shit-loads of data to it. h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0) chunk_data = str2bytes("z") * 0x8000 num_loops = 512 expected_size = num_loops * len(chunk_data) for i in range(num_loops): win32file.WriteFile(h, chunk_data, overlapped) win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE) overlapped.Offset = overlapped.Offset + len(chunk_data) h.Close() # Now read the data back overlapped overlapped = pywintypes.OVERLAPPED() evt = win32event.CreateEvent(None, 0, 0, None) overlapped.hEvent = evt desiredAccess = win32file.GENERIC_READ h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.OPEN_EXISTING, 0, 0) buffer = win32file.AllocateReadBuffer(0xFFFF) while 1: try: hr, data = win32file.ReadFile(h, buffer, overlapped) win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE) overlapped.Offset = overlapped.Offset + len(data) if not data is buffer: self.fail("Unexpected result from ReadFile - should be the same buffer we passed it") except win32api.error: break h.Close()
def testCompletionPortsQueued(self): class Foo: pass io_req_port = win32file.CreateIoCompletionPort(-1, None, 0, 0) overlapped = pywintypes.OVERLAPPED() overlapped.object = Foo() win32file.PostQueuedCompletionStatus(io_req_port, 0, 99, overlapped) errCode, bytes, key, overlapped = \ win32file.GetQueuedCompletionStatus(io_req_port, win32event.INFINITE) self.failUnlessEqual(errCode, 0) self.failUnless(isinstance(overlapped.object, Foo))
def run(self): self.running = True while self.running: errCode, bytes, key, overlapped = \ GetQueuedCompletionStatus(self.io_req_port, INFINITE) if key == ISAPI_SHUTDOWN and overlapped is None: break # Let the parent extension handle the command. dispatcher = self.extension.dispatch_map.get(key) if dispatcher is None: raise RuntimeError("Bad request '%s'" % (key,)) dispatcher(errCode, bytes, key, overlapped)
def SvcDoRun(self): # Starting up self.ReportServiceStatus(win32service.SERVICE_START_PENDING) if (self.starting() == True): self.ReportServiceStatus(win32service.SERVICE_RUNNING) win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) # Shutting Down self.stopping() self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def SvcDoRun(self): # __file__ == 'service_win32.py' exe_dir = os.path.dirname(os.path.dirname(__file__)) os.chdir(exe_dir) win32evtlogutil.ReportEvent( self._svc_name_, servicemanager.PYS_SERVICE_STARTED, 0, servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_, '')) config_file = os.path.join(exe_dir, 'agent.conf') config = Config(config_file) supervisor = Supervisor(config) win32evtlogutil.ReportEvent( self._svc_name_, servicemanager.PYS_SERVICE_STOPPED, 0, servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_, '')) thread = Thread(target=supervisor.start) thread.daemon = True thread.start() while True: rc = win32event.WaitForSingleObject( self.hWaitStop, win32event.INFINITE) if rc == win32event.WAIT_OBJECT_0: win32evtlogutil.ReportEvent( self._svc_name_, servicemanager.PYS_SERVICE_STOPPED, 0, servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_, '')) break
def run_as_admin(): procInfo = ShellExecuteEx(nShow=win32con.SW_SHOWNORMAL, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb='runas', lpFile=sys.executable) procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) return win32process.GetExitCodeProcess(procHandle)
def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) try: self.ReportServiceStatus(win32service.SERVICE_RUNNING) self.log('start') self.start() self.log('wait') win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE) self.log('done') except Exception as x: self.log('Exception : %s' % x) self.SvcStop()
def runAsAdmin(cmdLine=None, wait=True): if os.name != 'nt': raise RuntimeError, "This function is only implemented on Windows." import win32api import win32con import win32event import win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon python_exe = sys.executable if cmdLine is None: cmdLine = [python_exe] + sys.argv elif type(cmdLine) not in (types.TupleType, types.ListType): raise ValueError, "cmdLine is not a sequence." cmd = '"%s"' % (cmdLine[0],) # XXX TODO: isn't there a function or something we can call to massage command line params? params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]]) cmdDir = '' #showCmd = win32con.SW_SHOWNORMAL showCmd = win32con.SW_HIDE lpVerb = 'runas' # causes UAC elevation prompt. # print "Running", cmd, params # ShellExecute() doesn't seem to allow us to fetch the PID or handle # of the process, so we can't get anything useful from it. Therefore # the more complex ShellExecuteEx() must be used. # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd) procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) if wait: procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) # print "Process handle %s returned code %s" % (procHandle, rc) else: rc = None return rc
def runAsAdmin(cmdLine=None, wait=True): if os.name != 'nt': raise RuntimeError, "This function is only implemented on Windows." import win32api, win32con, win32event, win32process from win32com.shell.shell import ShellExecuteEx from win32com.shell import shellcon python_exe = sys.executable if cmdLine is None: cmdLine = [python_exe] + sys.argv elif type(cmdLine) not in (types.TupleType,types.ListType): raise ValueError, "cmdLine is not a sequence." cmd = '"%s"' % (cmdLine[0],) # XXX TODO: isn't there a function or something we can call to massage command line params? params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]]) cmdDir = '' showCmd = win32con.SW_SHOWNORMAL #showCmd = win32con.SW_HIDE lpVerb = 'runas' # causes UAC elevation prompt. # print "Running", cmd, params # ShellExecute() doesn't seem to allow us to fetch the PID or handle # of the process, so we can't get anything useful from it. Therefore # the more complex ShellExecuteEx() must be used. # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd) procInfo = ShellExecuteEx(nShow=showCmd, fMask=shellcon.SEE_MASK_NOCLOSEPROCESS, lpVerb=lpVerb, lpFile=cmd, lpParameters=params) if wait: procHandle = procInfo['hProcess'] obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE) rc = win32process.GetExitCodeProcess(procHandle) #print "Process handle %s returned code %s" % (procHandle, rc) else: rc = None return rc