Python signal.SIG_IGN Examples
The following are 30
code examples of signal.SIG_IGN().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
signal
, or try the search function
.
Example #1
Source File: UrlUpserter.py From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License | 8 votes |
def __init__(self, msg_queue, db_interface): self.response_queue = msg_queue self.log = logging.getLogger("Main.LinkAggregator") try: signal.signal(signal.SIGINT, signal.SIG_IGN) except ValueError: self.log.warning("Cannot configure job fetcher task to ignore SIGINT. May be an issue.") # LRU Cache with a maxsize of 1 million, and a TTL of 6 hours self.seen = cachetools.TTLCache(maxsize=1000 * 1000, ttl=60 * 60 * 6) self.queue_items = 0 self.link_count = 0 self.amqpUpdateCount = 0 self.deathCounter = 0 self.batched_links = [] self.pending_upserts = [] self.db_int = db_interface self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=6) self.check_init_func()
Example #2
Source File: driver_agent.py From octavia with Apache License 2.0 | 6 votes |
def _process_wrapper(exit_event, proc_name, function, agent_name=None): signal.signal(signal.SIGINT, signal.SIG_IGN) signal.signal(signal.SIGHUP, _mutate_config) if agent_name: process_title = 'octavia-driver-agent - {} -- {}'.format( proc_name, agent_name) else: process_title = 'octavia-driver-agent - {}'.format(proc_name) setproctitle.setproctitle(process_title) while not exit_event.is_set(): try: function(exit_event) except Exception as e: if agent_name: LOG.exception('Provider agent "%s" raised exception: %s. ' 'Restarting the "%s" provider agent.', agent_name, str(e), agent_name) else: LOG.exception('%s raised exception: %s. ' 'Restarting %s.', proc_name, str(e), proc_name) time.sleep(1) continue break
Example #3
Source File: test_break.py From BinderFilter with MIT License | 6 votes |
def testHandlerReplacedButCalled(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") # If our handler has been replaced (is no longer installed) but is # called by the *new* handler, then it isn't safe to delay the # SIGINT and we should immediately delegate to the default handler unittest.installHandler() handler = signal.getsignal(signal.SIGINT) def new_handler(frame, signum): handler(frame, signum) signal.signal(signal.SIGINT, new_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass else: self.fail("replaced but delegated handler doesn't raise interrupt")
Example #4
Source File: test_break.py From BinderFilter with MIT License | 6 votes |
def testSecondInterrupt(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) os.kill(pid, signal.SIGINT) self.fail("Second KeyboardInterrupt not raised") try: test(result) except KeyboardInterrupt: pass else: self.fail("Second KeyboardInterrupt not raised") self.assertTrue(result.breakCaught)
Example #5
Source File: data-extractor.py From cloudml-samples with Apache License 2.0 | 6 votes |
def parallel_map(function, iterable): """Calls a function for every element in an iterable using multiple cores.""" if FORCE_DISABLE_MULTIPROCESSING: return [function(*args) for args in iterable] original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) num_threads = mp.cpu_count() * 2 pool = mp.Pool(processes=num_threads) signal.signal(signal.SIGINT, original_sigint_handler) p = pool.map_async(_function_wrapper, ((function, args) for args in iterable)) try: results = p.get(0xFFFFFFFF) except KeyboardInterrupt: pool.terminate() raise pool.close() return results
Example #6
Source File: signals.py From BinderFilter with MIT License | 6 votes |
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
Example #7
Source File: multiprocess.py From Computable with MIT License | 6 votes |
def _import_mp(): global Process, Queue, Pool, Event, Value, Array try: from multiprocessing import Manager, Process #prevent the server process created in the manager which holds Python #objects and allows other processes to manipulate them using proxies #to interrupt on SIGINT (keyboardinterrupt) so that the communication #channel between subprocesses and main process is still usable after #ctrl+C is received in the main process. old=signal.signal(signal.SIGINT, signal.SIG_IGN) m = Manager() #reset it back so main process will receive a KeyboardInterrupt #exception on ctrl+c signal.signal(signal.SIGINT, old) Queue, Pool, Event, Value, Array = ( m.Queue, m.Pool, m.Event, m.Value, m.Array ) except ImportError: warn("multiprocessing module is not available, multiprocess plugin " "cannot be used", RuntimeWarning)
Example #8
Source File: Task.py From mongodb_consistent_backup with Apache License 2.0 | 6 votes |
def __init__(self, task_name, manager, config, timer, base_dir, backup_dir, **kwargs): self.task_name = task_name self.manager = manager self.config = config self.timer = timer self.base_dir = base_dir self.backup_dir = backup_dir self.args = kwargs self.verbose = self.config.verbose self.runnning = False self.stopped = False self.completed = False self.exit_code = 255 self.thread_count = None self.cpu_count = cpu_count() self.compression_method = 'none' self.compression_supported = ['none'] self.timer_name = self.__class__.__name__ signal(SIGINT, SIG_IGN) signal(SIGTERM, self.close)
Example #9
Source File: signals.py From ironpython2 with Apache License 2.0 | 6 votes |
def __init__(self, default_handler): self.called = False self.original_handler = default_handler if isinstance(default_handler, (int, long)): 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
Example #10
Source File: signals.py From oss-ftp with MIT License | 6 votes |
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
Example #11
Source File: test_break.py From oss-ftp with MIT License | 6 votes |
def testSecondInterrupt(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) os.kill(pid, signal.SIGINT) self.fail("Second KeyboardInterrupt not raised") try: test(result) except KeyboardInterrupt: pass else: self.fail("Second KeyboardInterrupt not raised") self.assertTrue(result.breakCaught)
Example #12
Source File: test_break.py From oss-ftp with MIT License | 6 votes |
def testHandlerReplacedButCalled(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") # If our handler has been replaced (is no longer installed) but is # called by the *new* handler, then it isn't safe to delay the # SIGINT and we should immediately delegate to the default handler unittest.installHandler() handler = signal.getsignal(signal.SIGINT) def new_handler(frame, signum): handler(frame, signum) signal.signal(signal.SIGINT, new_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass else: self.fail("replaced but delegated handler doesn't raise interrupt")
Example #13
Source File: test_break.py From ironpython2 with Apache License 2.0 | 6 votes |
def testHandlerReplacedButCalled(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") # If our handler has been replaced (is no longer installed) but is # called by the *new* handler, then it isn't safe to delay the # SIGINT and we should immediately delegate to the default handler unittest.installHandler() handler = signal.getsignal(signal.SIGINT) def new_handler(frame, signum): handler(frame, signum) signal.signal(signal.SIGINT, new_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass else: self.fail("replaced but delegated handler doesn't raise interrupt")
Example #14
Source File: rc_connect.py From reconchess with BSD 3-Clause "New" or "Revised" License | 6 votes |
def accept_invitation_and_play(server_url, auth, invitation_id, bot_cls, finished): # make sure this process doesn't react to interrupt signals signal.signal(signal.SIGTERM, signal.SIG_IGN) signal.signal(signal.SIGINT, signal.SIG_IGN) print('[{}] Accepting invitation {}.'.format(datetime.now(), invitation_id)) server = RBCServer(server_url, auth) game_id = server.accept_invitation(invitation_id) print('[{}] Invitation {} accepted. Playing game {}.'.format(datetime.now(), invitation_id, game_id)) try: play_remote_game(server_url, game_id, auth, bot_cls()) print('[{}] Finished game {}'.format(datetime.now(), game_id)) except: print('[{}] Fatal error in game {}:'.format(datetime.now(), game_id)) traceback.print_exc() server.error_resign(game_id) finally: server.finish_invitation(invitation_id) finished.value = True
Example #15
Source File: signals.py From jawfish with MIT License | 6 votes |
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
Example #16
Source File: multiprocess.py From locality-sensitive-hashing with MIT License | 6 votes |
def _import_mp(): global Process, Queue, Pool, Event, Value, Array try: from multiprocessing import Manager, Process #prevent the server process created in the manager which holds Python #objects and allows other processes to manipulate them using proxies #to interrupt on SIGINT (keyboardinterrupt) so that the communication #channel between subprocesses and main process is still usable after #ctrl+C is received in the main process. old=signal.signal(signal.SIGINT, signal.SIG_IGN) m = Manager() #reset it back so main process will receive a KeyboardInterrupt #exception on ctrl+c signal.signal(signal.SIGINT, old) Queue, Pool, Event, Value, Array = ( m.Queue, m.Pool, m.Event, m.Value, m.Array ) except ImportError: warn("multiprocessing module is not available, multiprocess plugin " "cannot be used", RuntimeWarning)
Example #17
Source File: model_analyzer.py From Generative-ConvACs with MIT License | 6 votes |
def init_worker(num_instances, kernel_h, kernel_w, pad, stride, indices, pdfs): global g_num_instances g_num_instances = num_instances global g_kernel_h g_kernel_h = kernel_h global g_kernel_w g_kernel_w = kernel_w global g_pad g_pad = pad global g_stride g_stride = stride global g_indices g_indices = indices global g_pdfs g_pdfs = pdfs signal.signal(signal.SIGINT, signal.SIG_IGN) np.random.seed(None)
Example #18
Source File: test_break.py From ironpython2 with Apache License 2.0 | 6 votes |
def testSecondInterrupt(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) os.kill(pid, signal.SIGINT) self.fail("Second KeyboardInterrupt not raised") try: test(result) except KeyboardInterrupt: pass else: self.fail("Second KeyboardInterrupt not raised") self.assertTrue(result.breakCaught)
Example #19
Source File: worker.py From sregistry-cli with Mozilla Public License 2.0 | 5 votes |
def init_worker(): signal.signal(signal.SIGINT, signal.SIG_IGN)
Example #20
Source File: autoreload.py From bioforum with MIT License | 5 votes |
def ensure_echo_on(): if termios: fd = sys.stdin if fd.isatty(): attr_list = termios.tcgetattr(fd) if not attr_list[3] & termios.ECHO: attr_list[3] |= termios.ECHO if hasattr(signal, 'SIGTTOU'): old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN) else: old_handler = None termios.tcsetattr(fd, termios.TCSANOW, attr_list) if old_handler is not None: signal.signal(signal.SIGTTOU, old_handler)
Example #21
Source File: py_unittest.py From clusterfuzz with Apache License 2.0 | 5 votes |
def test_worker_init(): """Initialise test worker process.""" if platform.system() != 'Windows': # Prevent KeyboardInterrupt error output. signal.signal(signal.SIGINT, signal.SIG_IGN)
Example #22
Source File: tunnel.py From vnpy_crypto with MIT License | 5 votes |
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None): """Function for actually starting a paramiko tunnel, to be passed to multiprocessing.Process(target=this), and not called directly. """ username, server, port = _split_server(server) client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) try: client.connect(server, port, username=username, key_filename=keyfile, look_for_keys=True, password=password) # except paramiko.AuthenticationException: # if password is None: # password = getpass("%s@%s's password: "%(username, server)) # client.connect(server, port, username=username, password=password) # else: # raise except Exception as e: print('*** Failed to connect to %s:%d: %r' % (server, port, e)) sys.exit(1) # Don't let SIGINT kill the tunnel subprocess signal.signal(signal.SIGINT, signal.SIG_IGN) try: forward_tunnel(lport, remoteip, rport, client.get_transport()) except KeyboardInterrupt: print('SIGINT: Port forwarding stopped cleanly') sys.exit(0) except Exception as e: print("Port forwarding stopped uncleanly: %s"%e) sys.exit(255)
Example #23
Source File: utils.py From retinanet-examples with BSD 3-Clause "New" or "Revised" License | 5 votes |
def ignore_sigint(): handler = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, signal.SIG_IGN) try: yield finally: signal.signal(signal.SIGINT, handler)
Example #24
Source File: mainLoop.py From GroundHog with BSD 3-Clause "New" or "Revised" License | 5 votes |
def save(self): # ignore keyboard interrupt while saving s = signal.signal(signal.SIGINT, signal.SIG_IGN) numpy.savez(self.state['prefix']+'timing.npz', **self.timings) if self.state['overwrite']: self.model.save(self.state['prefix']+'model.npz') else: self.model.save(self.state['prefix'] + 'model%d.npz' % self.save_iter) cPickle.dump(self.state, open(self.state['prefix']+'state.pkl', 'w')) self.save_iter += 1 signal.signal(signal.SIGINT, s) # FIXME
Example #25
Source File: data_handler.py From cortex with BSD 3-Clause "New" or "Revised" License | 5 votes |
def add_dataset(self, source, dataset_entrypoint, n_workers=4, shuffle=True, DataLoader=None): DataLoader = (DataLoader or dataset_entrypoint._dataloader_class or torch.utils.data.DataLoader) if len(dataset_entrypoint._datasets) == 0: raise ValueError('No datasets found in entrypoint') loaders = {} for k, dataset in dataset_entrypoint._datasets.items(): N = len(dataset) dataset_entrypoint._dims['N_' + k] = N if isinstance(self.batch_size, dict): try: self.batch_size[k] except KeyError: self.batch_size[k] = self.batch_size_ finally: batch_size = self.batch_size[k] else: self.batch_size_ = self.batch_size self.batch_size = {k: self.batch_size_} batch_size = self.batch_size_ loaders[k] = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=n_workers, worker_init_fn=lambda x: signal.signal(signal.SIGINT, signal.SIG_IGN)) self.dims[source] = dataset_entrypoint._dims self.input_names[source] = dataset_entrypoint._input_names self.loaders[source] = loaders
Example #26
Source File: inputhook.py From Computable with MIT License | 5 votes |
def _ignore_CTRL_C_posix(): """Ignore CTRL+C (SIGINT).""" signal.signal(signal.SIGINT, signal.SIG_IGN)
Example #27
Source File: generate_missing_data.py From Generative-ConvACs with MIT License | 5 votes |
def init_worker(): signal.signal(signal.SIGINT, signal.SIG_IGN) np.random.seed(None) # Utilities for loading and saving images to/from numpy arrays
Example #28
Source File: generate_norb_small.py From Generative-ConvACs with MIT License | 5 votes |
def init_worker(): signal.signal(signal.SIGINT, signal.SIG_IGN) np.random.seed(None)
Example #29
Source File: _service_manager.py From cotyledon with Apache License 2.0 | 5 votes |
def _reload(self): """reload all children posix only """ self._run_hooks('reload') # Reset forktimes to respawn services quickly self._forktimes = [] signal.signal(signal.SIGHUP, signal.SIG_IGN) os.killpg(0, signal.SIGHUP) signal.signal(signal.SIGHUP, self._signal_catcher)
Example #30
Source File: utility.py From MIDAS with GNU General Public License v3.0 | 5 votes |
def parallel(function, argument_list, threads): """ Based on: https://gist.github.com/admackin/003dd646e5fadee8b8d6 """ import multiprocessing as mp import signal import time def init_worker(): signal.signal(signal.SIGINT, signal.SIG_IGN) pool = mp.Pool(int(threads), init_worker) try: results = [] for arguments in argument_list: p = pool.apply_async(function, args=arguments) results.append(p) pool.close() while True: if all(r.ready() for r in results): return [r.get() for r in results] time.sleep(1) except KeyboardInterrupt: pool.terminate() pool.join() sys.exit("\nKeyboardInterrupt")