我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用signal.default_int_handler()。
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
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)
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)
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
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
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
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. # -----------------------------------------------------------------------
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)
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)
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()
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
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()
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
def allowInterrupts(): try: return signal.signal(signal.SIGINT, signal.default_int_handler) except ValueError: return None # pass (not on main thread)
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 #-----------------------------------------------------------------------------
def _allow_CTRL_C_posix(): """Take CTRL+C into account (SIGINT).""" signal.signal(signal.SIGINT, signal.default_int_handler)
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
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 #-----------------------------------------------------------------------------
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)
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)
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
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)
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)