Python signal 模块,default_int_handler() 实例源码

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

项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _handleSignals(self):
        """Install the signal handlers for the Twisted event loop."""
        try:
            import signal
        except ImportError:
            log.msg("Warning: signal module unavailable -- not installing signal handlers.")
            return

        if signal.getsignal(signal.SIGINT) == signal.default_int_handler:
            # only handle if there isn't already a handler, e.g. for Pdb.
            signal.signal(signal.SIGINT, self.sigInt)
        signal.signal(signal.SIGTERM, self.sigTerm)

        # Catch Ctrl-Break in windows
        if hasattr(signal, "SIGBREAK"):
            signal.signal(signal.SIGBREAK, self.sigBreak)

        if platformType == 'posix':
            signal.signal(signal.SIGCHLD, self._handleSigchld)
项目:devsecops-example-helloworld    作者:boozallen    | 项目源码 | 文件源码
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler
项目:trio    作者:python-trio    | 项目源码 | 文件源码
def ki_manager(deliver_cb, restrict_keyboard_interrupt_to_checkpoints):
    if (threading.current_thread() != threading.main_thread()
            or signal.getsignal(signal.SIGINT) != signal.default_int_handler):
        yield
        return

    def handler(signum, frame):
        assert signum == signal.SIGINT
        protection_enabled = ki_protection_enabled(frame)
        if protection_enabled or restrict_keyboard_interrupt_to_checkpoints:
            deliver_cb()
        else:
            raise KeyboardInterrupt

    signal.signal(signal.SIGINT, handler)
    try:
        yield
    finally:
        if signal.getsignal(signal.SIGINT) is handler:
            signal.signal(signal.SIGINT, signal.default_int_handler)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def _handleSignals(self):
        """Install the signal handlers for the Twisted event loop."""
        try:
            import signal
        except ImportError:
            log.msg("Warning: signal module unavailable -- not installing signal handlers.")
            return

        if signal.getsignal(signal.SIGINT) == signal.default_int_handler:
            # only handle if there isn't already a handler, e.g. for Pdb.
            signal.signal(signal.SIGINT, self.sigInt)
        signal.signal(signal.SIGTERM, self.sigTerm)

        # Catch Ctrl-Break in windows
        if hasattr(signal, "SIGBREAK"):
            signal.signal(signal.SIGBREAK, self.sigBreak)

        if platformType == 'posix':
            signal.signal(signal.SIGCHLD, self._handleSigchld)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def _kill_process(self, method, *args):
        # Do not inherit file handles from the parent.
        # It should fix failures on some platforms.
        # Also set the SIGINT handler to the default to make sure it's not
        # being ignored (some tests rely on that.)
        old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
        try:
            p = subprocess.Popen([sys.executable, "-c", """if 1:
                                 import sys, time
                                 sys.stdout.write('x\\n')
                                 sys.stdout.flush()
                                 time.sleep(30)
                                 """],
                                 close_fds=True,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
        finally:
            signal.signal(signal.SIGINT, old_handler)
        # Wait for the interpreter to be completely initialized before
        # sending any signal.
        p.stdout.read(1)
        getattr(p, method)(*args)
        return p
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def MakeValidSysOuts():
    if not isinstance(sys.stdout, SafeOutput):
        sys.stdout = sys.stderr = SafeOutput()
        # and for the sake of working around something I can't understand...
        # prevent keyboard interrupts from killing IIS
        import signal
        def noOp(a,b):
            # it would be nice to get to the bottom of this, so a warning to
            # the debug console can't hurt.
            print "WARNING: Ignoring keyboard interrupt from ActiveScripting engine"
        # If someone else has already redirected, then assume they know what they are doing!
        if signal.getsignal(signal.SIGINT) == signal.default_int_handler:
            try:
                signal.signal(signal.SIGINT, noOp)
            except ValueError:
                # Not the main thread - can't do much.
                pass
项目:CodeReader    作者:jasonrbr    | 项目源码 | 文件源码
def MakeValidSysOuts():
    if not isinstance(sys.stdout, SafeOutput):
        sys.stdout = sys.stderr = SafeOutput()
        # and for the sake of working around something I can't understand...
        # prevent keyboard interrupts from killing IIS
        import signal
        def noOp(a,b):
            # it would be nice to get to the bottom of this, so a warning to
            # the debug console can't hurt.
            print("WARNING: Ignoring keyboard interrupt from ActiveScripting engine")
        # If someone else has already redirected, then assume they know what they are doing!
        if signal.getsignal(signal.SIGINT) == signal.default_int_handler:
            try:
                signal.signal(signal.SIGINT, noOp)
            except ValueError:
                # Not the main thread - can't do much.
                pass
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def _kill_process(self, method, *args):
        # Do not inherit file handles from the parent.
        # It should fix failures on some platforms.
        # Also set the SIGINT handler to the default to make sure it's not
        # being ignored (some tests rely on that.)
        old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
        try:
            p = subprocess.Popen([sys.executable, "-c", """if 1:
                                 import sys, time
                                 sys.stdout.write('x\\n')
                                 sys.stdout.flush()
                                 time.sleep(30)
                                 """],
                                 close_fds=True,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
        finally:
            signal.signal(signal.SIGINT, old_handler)
        # Wait for the interpreter to be completely initialized before
        # sending any signal.
        p.stdout.read(1)
        getattr(p, method)(*args)
        return p
项目:empyrion-python-api    作者:huhlig    | 项目源码 | 文件源码
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler
项目:py4jdbc    作者:massmutual    | 项目源码 | 文件源码
def _set_signal_handlers(self):
        self.logger.info('Setting shutdown signal handlers.')
        default_int_handler = signal.default_int_handler
        for sig in self.shutdown_signals:
            handler = signal.getsignal(sig)
            if handler is self._shutdown_handler:
                continue
            elif handler not in [0, default_int_handler]:
                def _handler(*args, **kwargs):
                    try:
                        handler(*args, **kwargs)
                    except RecursionError:
                        return
                    default_int_handler(*args, **kwargs)
                handler = _handler
            else:
                handler = self._shutdown_handler
            signal.signal(sig, handler)

    # -----------------------------------------------------------------------
    # Runs the gateway subprocess and streams it's output to stdout.
    # -----------------------------------------------------------------------
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def _handleSignals(self):
        """
        Install the signal handlers for the Twisted event loop.
        """
        try:
            import signal
        except ImportError:
            log.msg("Warning: signal module unavailable -- "
                    "not installing signal handlers.")
            return

        if signal.getsignal(signal.SIGINT) == signal.default_int_handler:
            # only handle if there isn't already a handler, e.g. for Pdb.
            signal.signal(signal.SIGINT, self.sigInt)
        signal.signal(signal.SIGTERM, self.sigTerm)

        # Catch Ctrl-Break in windows
        if hasattr(signal, "SIGBREAK"):
            signal.signal(signal.SIGBREAK, self.sigBreak)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def __init__(self, default_handler):
        self.called = False
        self.original_handler = default_handler
        if isinstance(default_handler, int):
            if default_handler == signal.SIG_DFL:
                # Pretend it's signal.default_int_handler instead.
                default_handler = signal.default_int_handler
            elif default_handler == signal.SIG_IGN:
                # Not quite the same thing as SIG_IGN, but the closest we
                # can make it: do nothing.
                def default_handler(unused_signum, unused_frame):
                    pass
            else:
                raise TypeError("expected SIGINT signal handler to be "
                                "signal.SIG_IGN, signal.SIG_DFL, or a "
                                "callable object")
        self.default_handler = default_handler
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def _kill_process(self, method, *args):
        # Do not inherit file handles from the parent.
        # It should fix failures on some platforms.
        # Also set the SIGINT handler to the default to make sure it's not
        # being ignored (some tests rely on that.)
        old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
        try:
            p = subprocess.Popen([sys.executable, "-c", """if 1:
                                 import sys, time
                                 sys.stdout.write('x\\n')
                                 sys.stdout.flush()
                                 time.sleep(30)
                                 """],
                                 close_fds=True,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
        finally:
            signal.signal(signal.SIGINT, old_handler)
        # Wait for the interpreter to be completely initialized before
        # sending any signal.
        p.stdout.read(1)
        getattr(p, method)(*args)
        return p
项目:anthem    作者:camptocamp    | 项目源码 | 文件源码
def _build_odoo_env(self, odoo_args):
        odoo.tools.config.parse_config(odoo_args)
        dbname = odoo.tools.config['db_name']
        odoo.tools.config['workers'] = 0
        odoo.tools.config['xmlrpc'] = False
        if not dbname:
            argparse.ArgumentParser().error(
                "please provide a database name though Odoo options (either "
                "-d or an Odoo configuration file)"
            )
        logging.getLogger(odoo_logger).setLevel(logging.ERROR)
        odoo.service.server.start(preload=[], stop=True)

        # odoo.service.server.start() modifies the SIGINT signal by its own
        # one which in fact prevents us to stop anthem with Ctrl-c.
        # Restore the default one.
        signal.signal(signal.SIGINT, signal.default_int_handler)

        registry = odoo.modules.registry.RegistryManager.get(dbname)
        cr = registry.cursor()
        uid = odoo.SUPERUSER_ID
        Environment.reset()
        context = Environment(cr, uid, {})['res.users'].context_get()
        return Environment(cr, uid, context)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _installSignalHandlersAgain(self):
        """
        wx sometimes removes our own signal handlers, so re-add them.
        """
        try:
            # make _handleSignals happy:
            import signal
            signal.signal(signal.SIGINT, signal.default_int_handler)
        except ImportError:
            return
        self._handleSignals()
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def remove_signal_handler(self, sig):
        """Remove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        """
        self._check_signal(sig)
        try:
            del self._signal_handlers[sig]
        except KeyError:
            return False

        if sig == signal.SIGINT:
            handler = signal.default_int_handler
        else:
            handler = signal.SIG_DFL

        try:
            signal.signal(sig, handler)
        except OSError as exc:
            if exc.errno == errno.EINVAL:
                raise RuntimeError('sig {} cannot be caught'.format(sig))
            else:
                raise

        if not self._signal_handlers:
            try:
                signal.set_wakeup_fd(-1)
            except (ValueError, OSError) as exc:
                logger.info('set_wakeup_fd(-1) failed: %s', exc)

        return True
项目:pyrepl    作者:dajose    | 项目源码 | 文件源码
def twistedinteract(self):
        from twisted.internet import reactor
        from twisted.internet.abstract import FileDescriptor
        import signal
        outerself = self
        class Me(FileDescriptor):
            def fileno(self):
                """ We want to select on FD 0 """
                return 0

            def doRead(self):
                """called when input is ready"""
                try:
                    outerself.handle1()
                except EOFError:
                    reactor.stop()

        reactor.addReader(Me())
        reactor.callWhenRunning(signal.signal,
                                signal.SIGINT,
                                signal.default_int_handler)
        self.prepare()
        try:
            reactor.run()
        finally:
            self.restore()
项目:MIT-Thesis    作者:alec-heif    | 项目源码 | 文件源码
def worker(sock):
    """
    Called by a worker process after the fork().
    """
    signal.signal(SIGHUP, SIG_DFL)
    signal.signal(SIGCHLD, SIG_DFL)
    signal.signal(SIGTERM, SIG_DFL)
    # restore the handler for SIGINT,
    # it's useful for debugging (show the stacktrace before exit)
    signal.signal(SIGINT, signal.default_int_handler)

    # Read the socket using fdopen instead of socket.makefile() because the latter
    # seems to be very slow; note that we need to dup() the file descriptor because
    # otherwise writes also cause a seek that makes us miss data on the read side.
    infile = os.fdopen(os.dup(sock.fileno()), "rb", 65536)
    outfile = os.fdopen(os.dup(sock.fileno()), "wb", 65536)
    exit_code = 0
    try:
        worker_main(infile, outfile)
    except SystemExit as exc:
        exit_code = compute_real_exit_code(exc.code)
    finally:
        try:
            outfile.flush()
        except Exception:
            pass
    return exit_code
项目:pynapl    作者:marinuso    | 项目源码 | 文件源码
def allowInterrupts():
    try: return signal.signal(signal.SIGINT, signal.default_int_handler)
    except ValueError: return None # pass (not on main thread)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def glut_int_handler(signum, frame):
    # Catch sigint and print the defautl message
    signal.signal(signal.SIGINT, signal.default_int_handler)
    print('\nKeyboardInterrupt')
    # Need to reprint the prompt at this stage



#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def _allow_CTRL_C_posix():
    """Take CTRL+C into account (SIGINT)."""
    signal.signal(signal.SIGINT, signal.default_int_handler)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def glut_int_handler(signum, frame):
    # Catch sigint and print the defaultipyt   message
    signal.signal(signal.SIGINT, signal.default_int_handler)
    print('\nKeyboardInterrupt')
    # Need to reprint the prompt at this stage

# Initialisation code
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def _installSignalHandlersAgain(self):
        """
        wx sometimes removes our own signal handlers, so re-add them.
        """
        try:
            # make _handleSignals happy:
            import signal
            signal.signal(signal.SIGINT, signal.default_int_handler)
        except ImportError:
            return
        self._handleSignals()
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def glut_int_handler(signum, frame):
    # Catch sigint and print the defautl message
    signal.signal(signal.SIGINT, signal.default_int_handler)
    print '\nKeyboardInterrupt'
    # Need to reprint the prompt at this stage



#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
项目:txjuju    作者:juju    | 项目源码 | 文件源码
def tearDown(self):
        if log.defaultObserver is not None:
            log.defaultObserver.start()
        TestCase.tearDown(self)
        # Trial should restore the handler itself, but doesn't.
        # See bug #3888 in Twisted tracker.
        signal.signal(signal.SIGINT, signal.default_int_handler)
项目:golightan    作者:shirou    | 项目源码 | 文件源码
def remove_signal_handler(self, sig):
        """Remove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        """
        self._check_signal(sig)
        try:
            del self._signal_handlers[sig]
        except KeyError:
            return False

        if sig == signal.SIGINT:
            handler = signal.default_int_handler
        else:
            handler = signal.SIG_DFL

        try:
            signal.signal(sig, handler)
        except OSError as exc:
            if exc.errno == errno.EINVAL:
                raise RuntimeError('sig {} cannot be caught'.format(sig))
            else:
                raise

        if not self._signal_handlers:
            try:
                signal.set_wakeup_fd(-1)
            except (ValueError, OSError) as exc:
                logger.info('set_wakeup_fd(-1) failed: %s', exc)

        return True
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def glut_int_handler(signum, frame):
    # Catch sigint and print the defautl message
    signal.signal(signal.SIGINT, signal.default_int_handler)
    print('\nKeyboardInterrupt')
    # Need to reprint the prompt at this stage



#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _allow_CTRL_C_posix():
    """Take CTRL+C into account (SIGINT)."""
    signal.signal(signal.SIGINT, signal.default_int_handler)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def glut_int_handler(signum, frame):
    # Catch sigint and print the defaultipyt   message
    signal.signal(signal.SIGINT, signal.default_int_handler)
    print('\nKeyboardInterrupt')
    # Need to reprint the prompt at this stage

# Initialisation code
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def twistedinteract(self):
        from twisted.internet import reactor
        from twisted.internet.abstract import FileDescriptor
        import signal
        outerself = self
        class Me(FileDescriptor):
            def fileno(self):
                """ We want to select on FD 0 """
                return 0

            def doRead(self):
                """called when input is ready"""
                try:
                    outerself.handle1()
                except EOFError:
                    reactor.stop()

        reactor.addReader(Me())
        reactor.callWhenRunning(signal.signal,
                                signal.SIGINT,
                                signal.default_int_handler)
        self.prepare()
        try:
            reactor.run()
        finally:
            self.restore()
项目:pyspark    作者:v-v-vishnevskiy    | 项目源码 | 文件源码
def worker(sock):
    """
    Called by a worker process after the fork().
    """
    signal.signal(SIGHUP, SIG_DFL)
    signal.signal(SIGCHLD, SIG_DFL)
    signal.signal(SIGTERM, SIG_DFL)
    # restore the handler for SIGINT,
    # it's useful for debugging (show the stacktrace before exit)
    signal.signal(SIGINT, signal.default_int_handler)

    # Read the socket using fdopen instead of socket.makefile() because the latter
    # seems to be very slow; note that we need to dup() the file descriptor because
    # otherwise writes also cause a seek that makes us miss data on the read side.
    infile = os.fdopen(os.dup(sock.fileno()), "rb", 65536)
    outfile = os.fdopen(os.dup(sock.fileno()), "wb", 65536)
    exit_code = 0
    try:
        worker_main(infile, outfile)
    except SystemExit as exc:
        exit_code = compute_real_exit_code(exc.code)
    finally:
        try:
            outfile.flush()
        except Exception:
            pass
    return exit_code
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def remove_signal_handler(self, sig):
        """Remove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        """
        self._check_signal(sig)
        try:
            del self._signal_handlers[sig]
        except KeyError:
            return False

        if sig == signal.SIGINT:
            handler = signal.default_int_handler
        else:
            handler = signal.SIG_DFL

        try:
            signal.signal(sig, handler)
        except OSError as exc:
            if exc.errno == errno.EINVAL:
                raise RuntimeError('sig {} cannot be caught'.format(sig))
            else:
                raise

        if not self._signal_handlers:
            try:
                signal.set_wakeup_fd(-1)
            except (ValueError, OSError) as exc:
                logger.info('set_wakeup_fd(-1) failed: %s', exc)

        return True
项目:pygear    作者:amir-khakshour    | 项目源码 | 文件源码
def install_shutdown_handlers(function, override_sigint=True):
    """Install the given function as a signal handler for all common shutdown
    signals (such as SIGINT, SIGTERM, etc). If override_sigint is ``False`` the
    SIGINT handler won't be install if there is already a handler in place
    (e.g.  Pdb)
    """
    reactor._handleSignals()
    signal.signal(signal.SIGTERM, function)
    if signal.getsignal(signal.SIGINT) == signal.default_int_handler or \
            override_sigint:
        signal.signal(signal.SIGINT, function)
    # Catch Ctrl-Break in windows
    if hasattr(signal, "SIGBREAK"):
        signal.signal(signal.SIGBREAK, function)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def _installSignalHandlersAgain(self):
        """
        wx sometimes removes our own signal handlers, so re-add them.
        """
        try:
            # make _handleSignals happy:
            import signal
            signal.signal(signal.SIGINT, signal.default_int_handler)
        except ImportError:
            return
        self._handleSignals()
项目:pytest-odoo    作者:camptocamp    | 项目源码 | 文件源码
def pytest_cmdline_main(config):

    if (config.getoption('--odoo-database')
            or os.environ.get('OPENERP_SERVER')):
        options = []
        # Replace --odoo-<something> by --<something> and prepare the argument
        # to propagate to odoo.
        for option in ['--odoo-database', '--odoo-log-level']:
            value = config.getoption(option)
            if value:
                odoo_arg = '--%s' % option[7:]
                options.append('%s=%s' % (odoo_arg, value))

        odoo.tools.config.parse_config(options)

        if not odoo.tools.config['db_name']:
            # if you fall here, it means you have OPENERP_SERVER pointing
            # to a configuration file without 'database' configuration
            raise Exception(
                "please provide a database name in the Odoo configuration file"
            )

        odoo.service.server.start(preload=[], stop=True)
        # odoo.service.server.start() modifies the SIGINT signal by its own
        # one which in fact prevents us to stop anthem with Ctrl-c.
        # Restore the default one.
        signal.signal(signal.SIGINT, signal.default_int_handler)
        with odoo.api.Environment.manage():
            yield
    else:
        yield
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def remove_signal_handler(self, sig):
        """Remove a handler for a signal.  UNIX only.

        Return True if a signal handler was removed, False if not.
        """
        self._check_signal(sig)
        try:
            del self._signal_handlers[sig]
        except KeyError:
            return False

        if sig == signal.SIGINT:
            handler = signal.default_int_handler
        else:
            handler = signal.SIG_DFL

        try:
            signal.signal(sig, handler)
        except OSError as exc:
            if exc.errno == errno.EINVAL:
                raise RuntimeError('sig {} cannot be caught'.format(sig))
            else:
                raise

        if not self._signal_handlers:
            try:
                signal.set_wakeup_fd(-1)
            except (ValueError, OSError) as exc:
                logger.info('set_wakeup_fd(-1) failed: %s', exc)

        return True
项目:themole    作者:tiankonguse    | 项目源码 | 文件源码
def start(self):
        while True:
            try:
                signal.signal(signal.SIGINT, signal.default_int_handler)
                try:
                    #line = [i for i in input('#> ').strip().split(' ') if len(i) > 0]
                    line = input('#> ')
                except KeyboardInterrupt:
                    output_manager.line_break()
                    continue

                cmd_name = line.strip().split(' ')
                if len(cmd_name) > 0 and len(cmd_name[0]) > 0:
                    cmd = cmd_manager.find(cmd_name[0])
                    if cmd.requires_smart_parse():
                        line = self.completer.smart_parse(line)
                    else:
                        line = self.completer.nice_split(line)
                    signal.signal(signal.SIGINT, sigint_handler)
                    cmd.execute(self.mole, line[1:] if len(line) > 1 else [])
            except commands.CommandException as ex:
                output_manager.error(str(ex)).line_break()
                if ex.print_usage:
                    output_manager.normal(' Usage: {0}'.format(cmd.usage(line[0]))).line_break()
            except commands.CmdNotFoundException as ex:
                output_manager.error('Error: {0}'.format(ex)).line_break()
            except commands.QuietCommandException:
                pass
            except EOFError:
                output_manager.line_break()
                self.mole.abort_query()
                self.mole.threader.stop()
                exit(0)
项目:maas    作者:maas    | 项目源码 | 文件源码
def setup():
        # Run the SIGINT handler on SIGTERM; `svc -d` sends SIGTERM.
        signal.signal(signal.SIGTERM, signal.default_int_handler)
        # Ensure stdout and stderr are line-bufferred.
        if not sys.stdout.line_buffering:
            sys.stdout.flush()
            sys.stdout = io.TextIOWrapper(
                sys.stdout.buffer, sys.stdout.encoding,
                line_buffering=True)
        if not sys.stderr.line_buffering:
            sys.stderr.flush()
            sys.stderr = io.TextIOWrapper(
                sys.stderr.buffer, sys.stderr.encoding,
                line_buffering=True)
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def glut_int_handler(signum, frame):
    # Catch sigint and print the defautl message
    signal.signal(signal.SIGINT, signal.default_int_handler)
    print('\nKeyboardInterrupt')
    # Need to reprint the prompt at this stage



#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def _allow_CTRL_C_posix():
    """Take CTRL+C into account (SIGINT)."""
    signal.signal(signal.SIGINT, signal.default_int_handler)
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def glut_int_handler(signum, frame):
    # Catch sigint and print the defaultipyt   message
    signal.signal(signal.SIGINT, signal.default_int_handler)
    print('\nKeyboardInterrupt')
    # Need to reprint the prompt at this stage

# Initialisation code
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def glut_int_handler(signum, frame):
    # Catch sigint and print the defautl message
    signal.signal(signal.SIGINT, signal.default_int_handler)
    print('\nKeyboardInterrupt')
    # Need to reprint the prompt at this stage



#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def _allow_CTRL_C_posix():
    """Take CTRL+C into account (SIGINT)."""
    signal.signal(signal.SIGINT, signal.default_int_handler)