Python win32api 模块,SetConsoleCtrlHandler() 实例源码

我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用win32api.SetConsoleCtrlHandler()

项目:esys-pbi    作者:fsxfreak    | 项目源码 | 文件源码
def begin(queue, event=None):
  signal.signal(signal.SIGINT, sigint_handler)
  signal.signal(signal.SIGTERM, sigterm_handler)

  if sys.platform == 'win32':
    win.SetConsoleCtrlHandler(win_handler,1)

  load(queue)
  queue.put('CONNECTED')
  start()

  try:
    # linux signal handling
    while True:
      signal.pause()
  except AttributeError:
    # signal.pause() not implemented on windows
    while not event.is_set():
      time.sleep(1)
    print('event was set in bci, stopping')
    stop(queue)
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
def DebugService(cls, argv = []):
    # Run a service in "debug" mode.  Re-implements what pythonservice.exe
    # does when it sees a "-debug" param.
    # Currently only used by "frozen" (ie, py2exe) programs (but later may
    # end up being used for all services should we ever remove
    # pythonservice.exe)
    import servicemanager
    global g_debugService

    print "Debugging service %s - press Ctrl+C to stop." % (cls._svc_name_,)
    servicemanager.Debugging(True)
    servicemanager.PrepareToHostSingle(cls)
    g_debugService = cls(argv)
    # Setup a ctrl+c handler to simulate a "stop"
    win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, True)
    try:
        g_debugService.SvcRun()
    finally:
        win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, False)
        servicemanager.Debugging(False)
        g_debugService = None
项目:of    作者:OptimalBPM    | 项目源码 | 文件源码
def register_signals(_stop_handler):
    """
    Register a callback to gracefully handle the system being externally shut down (terminated)
    :param _stop_handler: A callback that helps the system shut down gracefully.
    """

    if _stop_handler:
        global stop_handler
        stop_handler = _stop_handler
    else:
        raise Exception("No stop handler, probably an internal error, needed for graceful shut down.")
    if os.name == "nt":
        try:
            import win32api
        except ImportError:
            version = ".".join(map(str, sys.version_info[:2]))
            raise Exception("pywin32 not installed for Python " + version)
        else:
            win32api.SetConsoleCtrlHandler(signal_handler_windows, True)
            write_to_log("Registered win32 ctrl handler", _category=EC_SERVICE, _severity=SEV_INFO)
    else:
        signal.signal(signal.SIGINT, signal_handler_unix)
        signal.signal(signal.SIGTERM, signal_handler_unix)
        signal.signal(signal.SIGQUIT, signal_handler_unix)
        signal.signal(signal.SIGHUP, signal_handler_unix)
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def DebugService(cls, argv = []):
    # Run a service in "debug" mode.  Re-implements what pythonservice.exe
    # does when it sees a "-debug" param.
    # Currently only used by "frozen" (ie, py2exe) programs (but later may
    # end up being used for all services should we ever remove
    # pythonservice.exe)
    import servicemanager
    global g_debugService

    print "Debugging service %s - press Ctrl+C to stop." % (cls._svc_name_,)
    servicemanager.Debugging(True)
    servicemanager.PrepareToHostSingle(cls)
    g_debugService = cls(argv)
    # Setup a ctrl+c handler to simulate a "stop"
    win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, True)
    try:
        g_debugService.SvcRun()
    finally:
        win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, False)
        servicemanager.Debugging(False)
        g_debugService = None
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def DebugService(cls, argv = []):
    # Run a service in "debug" mode.  Re-implements what pythonservice.exe
    # does when it sees a "-debug" param.
    # Currently only used by "frozen" (ie, py2exe) programs (but later may
    # end up being used for all services should we ever remove
    # pythonservice.exe)
    import servicemanager
    global g_debugService

    print("Debugging service %s - press Ctrl+C to stop." % (cls._svc_name_,))
    servicemanager.Debugging(True)
    servicemanager.PrepareToHostSingle(cls)
    g_debugService = cls(argv)
    # Setup a ctrl+c handler to simulate a "stop"
    win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, True)
    try:
        g_debugService.SvcRun()
    finally:
        win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, False)
        servicemanager.Debugging(False)
        g_debugService = None
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def stop(self):
        if not self.is_set:
            self.bus.log('Handler for console events already off.', level=40)
            return

        try:
            result = win32api.SetConsoleCtrlHandler(self.handle, 0)
        except ValueError:
            # "ValueError: The object has not been registered"
            result = 1

        if result == 0:
            self.bus.log('Could not remove SetConsoleCtrlHandler (error %r)' %
                         win32api.GetLastError(), level=40)
        else:
            self.bus.log('Removed handler for console events.', level=40)
            self.is_set = False
项目:watcher    作者:nosmokingbandit    | 项目源码 | 文件源码
def stop(self):
        if not self.is_set:
            self.bus.log('Handler for console events already off.', level=40)
            return

        try:
            result = win32api.SetConsoleCtrlHandler(self.handle, 0)
        except ValueError:
            # "ValueError: The object has not been registered"
            result = 1

        if result == 0:
            self.bus.log('Could not remove SetConsoleCtrlHandler (error %r)' %
                         win32api.GetLastError(), level=40)
        else:
            self.bus.log('Removed handler for console events.', level=40)
            self.is_set = False
项目:esys-pbi    作者:fsxfreak    | 项目源码 | 文件源码
def begin(queue, event=None):
  signal.signal(signal.SIGINT, sigint_handler)
  signal.signal(signal.SIGTERM, sigterm_handler)

  if sys.platform == 'win32':
    win.SetConsoleCtrlHandler(win_handler, 1)

  load(queue)
  start()

  while True:
    try:
      signal.pause()
    except AttributeError:
    # signal.pause() not implemented on windows
      while not event.is_set():
        time.sleep(1)
    print('event was set in graphing utility, stopping')
    stop()
项目:esys-pbi    作者:fsxfreak    | 项目源码 | 文件源码
def begin(queue, event=None):
  # TODO generalize to command line args
  if sys.platform == 'win32':
    win.SetConsoleCtrlHandler(win_handler, 1)

  load('../stimulus-config/test.yml')

  while True:
    msg = queue.get()
    if msg == 'BEGIN':
      break

  start(event)

  queue.put('FINISHED')
项目:incubator-milagro-mfa-server    作者:apache    | 项目源码 | 文件源码
def installService(cls, name, display_name=None, stay_alive=True):
    cls._svc_name_ = name
    cls._svc_display_name_ = display_name or name
    try:
        module_path = modules[cls.__module__].__file__
    except AttributeError:
        # maybe py2exe went by
        from sys import executable
        module_path = executable
    module_file = splitext(abspath(module_path))[0]
    cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)
    if stay_alive:
        win32api.SetConsoleCtrlHandler(lambda x: True, True)
    try:
        win32serviceutil.InstallService(
            cls._svc_reg_class_,
            cls._svc_name_,
            cls._svc_display_name_,
            startType=win32service.SERVICE_AUTO_START
        )
        print 'Installing service %s... done' % name
        win32serviceutil.StartService(
            cls._svc_name_
        )
        print 'Starting service %s... done' % name
        print '\nAll done!'

    except Exception, x:
        print str(x)
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def start(self):
        if self.is_set:
            self.bus.log('Handler for console events already set.', level=40)
            return

        result = win32api.SetConsoleCtrlHandler(self.handle, 1)
        if result == 0:
            self.bus.log('Could not SetConsoleCtrlHandler (error %r)' %
                         win32api.GetLastError(), level=40)
        else:
            self.bus.log('Set handler for console events.', level=40)
            self.is_set = True
项目:jinjabread    作者:Inveracity    | 项目源码 | 文件源码
def enable_ctrl_logoff_handler():
    if HAS_WIN32API:
        win32api.SetConsoleCtrlHandler(_win_console_event_handler, 1)
项目:FTPwalker    作者:Bohdan-Khomtchouk    | 项目源码 | 文件源码
def instart(cls, name, display_name=None, stay_alive=True):
    ''' Install and  Start (auto) a Service
        cls : the class (derived from Service) that implement the Service
        name : Service name
        display_name : the name displayed in the service manager
        stay_alive : Service will stop on logout if False
    '''
    cls._svc_name_ = name
    cls._svc_display_name_ = display_name or name
    try:
        module_path = modules[cls.__module__].__file__
    except AttributeError:
        # maybe py2exe went by
        from sys import executable
        module_path = executable
    module_file = splitext(abspath(module_path))[0]
    cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)
    if stay_alive:
        win32api.SetConsoleCtrlHandler(lambda x: True, True)
    try:
        win32serviceutil.InstallService(
            cls._svc_reg_class_,
            cls._svc_name_,
            cls._svc_display_name_,
            startType=win32service.SERVICE_AUTO_START
        )
        print('Install ok')
        win32serviceutil.StartService(
            cls._svc_name_
        )
        print('Start ok')
    except Exception as x:
        print(str(x))
项目:watcher    作者:nosmokingbandit    | 项目源码 | 文件源码
def start(self):
        if self.is_set:
            self.bus.log('Handler for console events already set.', level=40)
            return

        result = win32api.SetConsoleCtrlHandler(self.handle, 1)
        if result == 0:
            self.bus.log('Could not SetConsoleCtrlHandler (error %r)' %
                         win32api.GetLastError(), level=40)
        else:
            self.bus.log('Set handler for console events.', level=40)
            self.is_set = True
项目:ZServer    作者:zopefoundation    | 项目源码 | 文件源码
def __init__(self):
        self.registry = {}
        self.event_handles = {}
        self.admin_event_handle = win32event.CreateEvent(None, 0, 0, None)
        self.shutdown_requested = False
        # Register a "console control handler" for Ctrl+C/Break notification.
        SetConsoleCtrlHandler(consoleCtrlHandler)

        # Start the thread that is watching for events.
        thread = threading.Thread(target=self.signalCheckerThread)
        # If something goes terribly wrong, don't wait for this thread!
        thread.setDaemon(True)
        thread.start()
        self.signal_thread = thread