Python win32event 模块,WAIT_OBJECT_0 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用win32event.WAIT_OBJECT_0

项目:aquests    作者:hansroh    | 项目源码 | 文件源码
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)
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
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
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
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()
项目:aquests    作者:hansroh    | 项目源码 | 文件源码
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)
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
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
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
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()
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
    """
    Run cmd as a child process and return exit code.
    mSec:  terminate cmd after specified number of milliseconds
    stdin, stdout, stderr:
           file objects for child I/O (use hStdin etc. to attach
           handles instead of files); default is caller's stdin,
           stdout & stderr;
    kw:    see Process.__init__ for more keyword options
    """
    if stdin is not None:
        kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
    if stdout is not None:
        kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
    if stderr is not None:
        kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
    child = Process(cmd, **kw)
    if child.wait(mSec) != win32event.WAIT_OBJECT_0:
        child.kill()
        raise WindowsError('process timeout exceeded')
    return child.exitCode()
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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()
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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")
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
    """
    Run cmd as a child process and return exit code.
    mSec:  terminate cmd after specified number of milliseconds
    stdin, stdout, stderr:
           file objects for child I/O (use hStdin etc. to attach
           handles instead of files); default is caller's stdin,
           stdout & stderr;
    kw:    see Process.__init__ for more keyword options
    """
    if stdin is not None:
        kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno())
    if stdout is not None:
        kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno())
    if stderr is not None:
        kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno())
    child = Process(cmd, **kw)
    if child.wait(mSec) != win32event.WAIT_OBJECT_0:
        child.kill()
        raise WindowsError('process timeout exceeded')
    return child.exitCode()
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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()
项目:viewvc    作者:viewvc    | 项目源码 | 文件源码
def eof(self):
    ### should be calling file.eof() here instead of file.close(), there
    ### may be data in the pipe or buffer after the process exits
    if sys.platform == "win32":
      r = win32event.WaitForMultipleObjects(self.wait_for, 1, 0)
      if r == win32event.WAIT_OBJECT_0:
        self.file.close()
        self.file = None
        return win32process.GetExitCodeProcess(self.child_pid)
      return None

    if self.thread and self.thread.isAlive():
      return None

    pid, status = os.waitpid(self.child_pid, os.WNOHANG)
    if pid:
      self.file.close()
      self.file = None
      return status
    return None
项目:ZServer    作者:zopefoundation    | 项目源码 | 文件源码
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")
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
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
项目:pycos    作者:pgiri    | 项目源码 | 文件源码
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
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def checkWork(self):
        if win32event.WaitForSingleObject(self.proc.hProcess, 0) != win32event.WAIT_OBJECT_0:
            return 0
        exitCode = win32process.GetExitCodeProcess(self.proc.hProcess)
        if exitCode == 0:
            err = error.ProcessDone(exitCode)
        else:
            err = error.ProcessTerminated(exitCode)
        self.deactivate()
        self.proc.protocol.processEnded(failure.Failure(err))
        return 0
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
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
        # Seems to be a leak here I can't locate :(
        #self.failUnlessEqual(pythoncom._GetInterfaceCount(), 0)
        #self.failUnlessEqual(pythoncom._GetGatewayCount(), 0)
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def TestExplorerEvents():
    iexplore = win32com.client.DispatchWithEvents(
        "InternetExplorer.Application", ExplorerEvents)

    thread = win32api.GetCurrentThreadId()
    print 'TestExplorerEvents created IE object on thread %d'%thread

    iexplore.Visible = 1
    try:
        iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm'))
    except pythoncom.com_error, details:
        print "Warning - could not open the test HTML file", details

    # In this free-threaded example, we can simply wait until an event has 
    # been set - we will give it 2 seconds before giving up.
    rc = win32event.WaitForSingleObject(iexplore.event, 2000)
    if rc != win32event.WAIT_OBJECT_0:
        print "Document load event FAILED to fire!!!"

    iexplore.Quit()
    # Now we can do the same thing to wait for exit!
    # Although Quit generates events, in this free-threaded world we
    # do *not* need to run any message pumps.

    rc = win32event.WaitForSingleObject(iexplore.event, 2000)
    if rc != win32event.WAIT_OBJECT_0:
        print "OnQuit event FAILED to fire!!!"

    iexplore = None
    print "Finished the IE event sample!"
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
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
        # Seems to be a leak here I can't locate :(
        #self.failUnlessEqual(pythoncom._GetInterfaceCount(), 0)
        #self.failUnlessEqual(pythoncom._GetGatewayCount(), 0)
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def TestExplorerEvents():
    iexplore = win32com.client.DispatchWithEvents(
        "InternetExplorer.Application", ExplorerEvents)

    thread = win32api.GetCurrentThreadId()
    print 'TestExplorerEvents created IE object on thread %d'%thread

    iexplore.Visible = 1
    try:
        iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm'))
    except pythoncom.com_error, details:
        print "Warning - could not open the test HTML file", details

    # In this free-threaded example, we can simply wait until an event has 
    # been set - we will give it 2 seconds before giving up.
    rc = win32event.WaitForSingleObject(iexplore.event, 2000)
    if rc != win32event.WAIT_OBJECT_0:
        print "Document load event FAILED to fire!!!"

    iexplore.Quit()
    # Now we can do the same thing to wait for exit!
    # Although Quit generates events, in this free-threaded world we
    # do *not* need to run any message pumps.

    rc = win32event.WaitForSingleObject(iexplore.event, 2000)
    if rc != win32event.WAIT_OBJECT_0:
        print "OnQuit event FAILED to fire!!!"

    iexplore = None
    print "Finished the IE event sample!"
项目:execnet    作者:pytest-dev    | 项目源码 | 文件源码
def SvcDoRun(self):
        # Redirect stdout and stderr to prevent "IOError: [Errno 9]
        # Bad file descriptor". Windows services don't have functional
        # output streams.
        sys.stdout = sys.stderr = open('nul', 'w')

        # Write a 'started' event to the event log...
        win32evtlogutil.ReportEvent(self._svc_display_name_,
                                    servicemanager.PYS_SERVICE_STARTED,
                                    0,  # category
                                    servicemanager.EVENTLOG_INFORMATION_TYPE,
                                    (self._svc_name_, ''))
        print("Begin: %s" % (self._svc_display_name_))

        hostport = ':8888'
        print('Starting py.execnet SocketServer on %s' % hostport)
        serversock = socketserver.bind_and_listen(hostport)
        thread = threading.Thread(
            target=socketserver.startserver,
            args=(serversock,),
            kwargs={'loop': True})
        thread.setDaemon(True)
        thread.start()

        # wait to be stopped or self.WAIT_TIME to pass
        while True:
            result = win32event.WaitForSingleObject(
                self.hWaitStop, self.WAIT_TIME)
            if result == win32event.WAIT_OBJECT_0:
                break

        # write a 'stopped' event to the event log.
        win32evtlogutil.ReportEvent(self._svc_display_name_,
                                    servicemanager.PYS_SERVICE_STOPPED,
                                    0,  # category
                                    servicemanager.EVENTLOG_INFORMATION_TYPE,
                                    (self._svc_name_, ''))
        print("End: %s" % appname)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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()
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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()
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def checkWork(self):
        if win32event.WaitForSingleObject(self.proc.hProcess, 0) != win32event.WAIT_OBJECT_0:
            return 0
        exitCode = win32process.GetExitCodeProcess(self.proc.hProcess)
        if exitCode == 0:
            err = error.ProcessDone(exitCode)
        else:
            err = error.ProcessTerminated(exitCode)
        self.deactivate()
        self.proc.protocol.processEnded(failure.Failure(err))
        return 0
项目:isf    作者:w3h    | 项目源码 | 文件源码
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
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def kill(self, gracePeriod=5000):
        """
        Kill process. Try for an orderly shutdown via WM_CLOSE.  If
        still running after gracePeriod (5 sec. default), terminate.
        """
        win32gui.EnumWindows(self.__close__, 0)
        if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
            win32process.TerminateProcess(self.hProcess, 0)
            win32api.Sleep(100) # wait for resources to be released
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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!")
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def Connect(entryName, bUseCallback):
    if bUseCallback:
        theCallback = Callback
        win32event.ResetEvent(callbackEvent)
    else:
        theCallback = None
    #       in order to *use* the username/password of a particular dun entry, one must
    #       explicitly get those params under win95....
    try:
        dp, b = win32ras.GetEntryDialParams( None, entryName )
    except:
        print "Couldn't find DUN entry: %s" % entryName
    else:
        hras, rc = win32ras.Dial(None, None, (entryName, "", "", dp[ 3 ], dp[ 4 ], ""),theCallback)
    #       hras, rc = win32ras.Dial(None, None, (entryName, ),theCallback)
    #       print hras, rc
        if not bUseCallback and rc != 0:
            print "Could not dial the RAS connection:", win32ras.GetErrorString(rc)
            hras = HangUp( hras )
        #       don't wait here if there's no need to....
        elif bUseCallback and win32event.WaitForSingleObject(callbackEvent, 60000)!=win32event.WAIT_OBJECT_0:
            print "Gave up waiting for the process to complete!"
            #       sdk docs state one must explcitly hangup, even if there's an error....
            try:
                cs = win32ras.GetConnectStatus( hras )
            except:
                #       on error, attempt a hang up anyway....
                hras = HangUp( hras )
            else:
                if int( cs[ 0 ] ) == win32ras.RASCS_Disconnected:
                    hras = HangUp( hras )
    return hras, rc
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def testWaitableFireLong(self):
        h = win32event.CreateWaitableTimer(None, 0, None)
        dt = int2long(-160) # 160 ns.
        win32event.SetWaitableTimer(h, dt, 0, None, None, 0)
        rc = win32event.WaitForSingleObject(h, 1000)
        self.failUnlessEqual(rc, win32event.WAIT_OBJECT_0)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def assertSignaled(self, event):
        self.assertEquals(win32event.WaitForSingleObject(event, 0),
                          win32event.WAIT_OBJECT_0)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def testReleaseMutex(self):
        mutex = win32event.CreateMutex(None, True, None)
        res = win32event.ReleaseMutex(mutex)
        self.assertEqual(res, None)
        res = win32event.WaitForSingleObject(mutex, 0)
        self.assertEqual(res, win32event.WAIT_OBJECT_0)
        mutex.close()
        self.assertRaises(pywintypes.error, win32event.ReleaseMutex, mutex)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def _watcherThreadOverlapped(self, dn, dh, changes):
        flags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME
        buf = win32file.AllocateReadBuffer(8192)
        overlapped = pywintypes.OVERLAPPED()
        overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
        while 1:
            win32file.ReadDirectoryChangesW(dh,
                                            buf,
                                            False, #sub-tree
                                            flags,
                                            overlapped)
            # Wait for our event, or for 5 seconds.
            rc = win32event.WaitForSingleObject(overlapped.hEvent, 5000)
            if rc == win32event.WAIT_OBJECT_0:
                # got some data!  Must use GetOverlappedResult to find out
                # how much is valid!  0 generally means the handle has
                # been closed.  Blocking is OK here, as the event has
                # already been set.
                nbytes = win32file.GetOverlappedResult(dh, overlapped, True)
                if nbytes:
                    bits = win32file.FILE_NOTIFY_INFORMATION(buf, nbytes)
                    changes.extend(bits)
                else:
                    # This is "normal" exit - our 'tearDown' closes the
                    # handle.
                    # print "looks like dir handle was closed!"
                    return
            else:
                print "ERROR: Watcher thread timed-out!"
                return # kill the thread!
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def connect_thread_runner(self, expect_payload, giveup_event):
        # As Windows 2000 doesn't do ConnectEx, we need to use a non-blocking
        # accept, as our test connection may never come.  May as well use
        # AcceptEx for this...
        listener = socket.socket()
        self.addr = ('localhost', random.randint(10000,64000))
        listener.bind(self.addr)
        listener.listen(1)

        # create accept socket
        accepter = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # An overlapped
        overlapped = pywintypes.OVERLAPPED()
        overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
        # accept the connection.
        if expect_payload:
            buf_size = 1024
        else:
            # when we don't expect data we must be careful to only pass the
            # exact number of bytes for the endpoint data...
            buf_size = win32file.CalculateSocketEndPointSize(listener)

        buffer = win32file.AllocateReadBuffer(buf_size)
        win32file.AcceptEx(listener, accepter, buffer, overlapped)
        # wait for the connection or our test to fail.
        events = giveup_event, overlapped.hEvent
        rc = win32event.WaitForMultipleObjects(events, False, 2000)
        if rc == win32event.WAIT_TIMEOUT:
            self.fail("timed out waiting for a connection")
        if rc == win32event.WAIT_OBJECT_0:
            # Our main thread running the test failed and will never connect.
            return
        # must be a connection.
        nbytes = win32file.GetOverlappedResult(listener.fileno(), overlapped, False)
        if expect_payload:
            self.request = buffer[:nbytes]
        accepter.send(str2bytes('some expected response'))
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
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
        # Seems to be a leak here I can't locate :(
        #self.failUnlessEqual(pythoncom._GetInterfaceCount(), 0)
        #self.failUnlessEqual(pythoncom._GetGatewayCount(), 0)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def TestExplorerEvents():
    iexplore = win32com.client.DispatchWithEvents(
        "InternetExplorer.Application", ExplorerEvents)

    thread = win32api.GetCurrentThreadId()
    print 'TestExplorerEvents created IE object on thread %d'%thread

    iexplore.Visible = 1
    try:
        iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm'))
    except pythoncom.com_error, details:
        print "Warning - could not open the test HTML file", details

    # In this free-threaded example, we can simply wait until an event has 
    # been set - we will give it 2 seconds before giving up.
    rc = win32event.WaitForSingleObject(iexplore.event, 2000)
    if rc != win32event.WAIT_OBJECT_0:
        print "Document load event FAILED to fire!!!"

    iexplore.Quit()
    # Now we can do the same thing to wait for exit!
    # Although Quit generates events, in this free-threaded world we
    # do *not* need to run any message pumps.

    rc = win32event.WaitForSingleObject(iexplore.event, 2000)
    if rc != win32event.WAIT_OBJECT_0:
        print "OnQuit event FAILED to fire!!!"

    iexplore = None
    print "Finished the IE event sample!"
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def kill(self, gracePeriod=5000):
        """
        Kill process. Try for an orderly shutdown via WM_CLOSE.  If
        still running after gracePeriod (5 sec. default), terminate.
        """
        win32gui.EnumWindows(self.__close__, 0)
        if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0:
            win32process.TerminateProcess(self.hProcess, 0)
            win32api.Sleep(100) # wait for resources to be released
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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!")
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def testWaitableFireLong(self):
        h = win32event.CreateWaitableTimer(None, 0, None)
        dt = int2long(-160) # 160 ns.
        win32event.SetWaitableTimer(h, dt, 0, None, None, 0)
        rc = win32event.WaitForSingleObject(h, 1000)
        self.failUnlessEqual(rc, win32event.WAIT_OBJECT_0)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def testWaitableFire(self):
        h = win32event.CreateWaitableTimer(None, 0, None)
        dt = -160 # 160 ns.
        win32event.SetWaitableTimer(h, dt, 0, None, None, 0)
        rc = win32event.WaitForSingleObject(h, 1000)
        self.failUnlessEqual(rc, win32event.WAIT_OBJECT_0)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def assertSignaled(self, event):
        self.assertEquals(win32event.WaitForSingleObject(event, 0),
                          win32event.WAIT_OBJECT_0)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def testReleaseMutex(self):
        mutex = win32event.CreateMutex(None, True, None)
        res = win32event.ReleaseMutex(mutex)
        self.assertEqual(res, None)
        res = win32event.WaitForSingleObject(mutex, 0)
        self.assertEqual(res, win32event.WAIT_OBJECT_0)
        mutex.close()
        self.assertRaises(pywintypes.error, win32event.ReleaseMutex, mutex)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def _watcherThreadOverlapped(self, dn, dh, changes):
        flags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME
        buf = win32file.AllocateReadBuffer(8192)
        overlapped = pywintypes.OVERLAPPED()
        overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
        while 1:
            win32file.ReadDirectoryChangesW(dh,
                                            buf,
                                            False, #sub-tree
                                            flags,
                                            overlapped)
            # Wait for our event, or for 5 seconds.
            rc = win32event.WaitForSingleObject(overlapped.hEvent, 5000)
            if rc == win32event.WAIT_OBJECT_0:
                # got some data!  Must use GetOverlappedResult to find out
                # how much is valid!  0 generally means the handle has
                # been closed.  Blocking is OK here, as the event has
                # already been set.
                nbytes = win32file.GetOverlappedResult(dh, overlapped, True)
                if nbytes:
                    bits = win32file.FILE_NOTIFY_INFORMATION(buf, nbytes)
                    changes.extend(bits)
                else:
                    # This is "normal" exit - our 'tearDown' closes the
                    # handle.
                    # print "looks like dir handle was closed!"
                    return
            else:
                print("ERROR: Watcher thread timed-out!")
                return # kill the thread!
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
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
        # Seems to be a leak here I can't locate :(
        #self.failUnlessEqual(pythoncom._GetInterfaceCount(), 0)
        #self.failUnlessEqual(pythoncom._GetGatewayCount(), 0)
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def TestExplorerEvents():
    iexplore = win32com.client.DispatchWithEvents(
        "InternetExplorer.Application", ExplorerEvents)

    thread = win32api.GetCurrentThreadId()
    print('TestExplorerEvents created IE object on thread %d'%thread)

    iexplore.Visible = 1
    try:
        iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm'))
    except pythoncom.com_error as details:
        print("Warning - could not open the test HTML file", details)

    # In this free-threaded example, we can simply wait until an event has 
    # been set - we will give it 2 seconds before giving up.
    rc = win32event.WaitForSingleObject(iexplore.event, 2000)
    if rc != win32event.WAIT_OBJECT_0:
        print("Document load event FAILED to fire!!!")

    iexplore.Quit()
    # Now we can do the same thing to wait for exit!
    # Although Quit generates events, in this free-threaded world we
    # do *not* need to run any message pumps.

    rc = win32event.WaitForSingleObject(iexplore.event, 2000)
    if rc != win32event.WAIT_OBJECT_0:
        print("OnQuit event FAILED to fire!!!")

    iexplore = None
    print("Finished the IE event sample!")