本文整理汇总了Python中signal.signal方法的典型用法代码示例。如果您正苦于以下问题:Python signal.signal方法的具体用法?Python signal.signal怎么用?Python signal.signal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类signal
的用法示例。
在下文中一共展示了signal.signal方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def __init__(self, name=""):
self.barsToProgress = {}
self.t0 = time.time()
self.timeRemaining = "--"
self.status = "+"
self.name = name
self.lastRedraw = time.time()
self.isatty = sys.stdout.isatty()
try:
self.handleResize(None,None)
signal.signal(signal.SIGWINCH, self.handleResize)
self.signal_set = True
except:
self.term_width = 79
示例2: main
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def main(args, env):
if len(args.samples) < 2:
sys.stderr.write("Come on, give me at least two samples :(\n")
return 1
bass = Bass()
job = Job()
def received_sigterm(signal, frame):
sys.stderr.write("Received SIGINT\n")
bass.terminate()
signal.signal(signal.SIGINT, received_sigterm)
for path in args.samples:
job.add_sample(path)
bass.submit_job(job)
while not job.status in (Job.STATUS_ERROR, Job.STATUS_FINISHED, Job.STATUS_CANCELED):
time.sleep(1)
示例3: __call__
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def __call__(self, *args, **kwargs):
"""Trap ``SIGTERM`` and call wrapped function."""
self._caught_signal = None
# Register handler for SIGTERM, then call `self.func`
self.old_signal_handler = signal.getsignal(signal.SIGTERM)
signal.signal(signal.SIGTERM, self.signal_handler)
self.func(*args, **kwargs)
# Restore old signal handler
signal.signal(signal.SIGTERM, self.old_signal_handler)
# Handle any signal caught during execution
if self._caught_signal is not None:
signum, frame = self._caught_signal
if callable(self.old_signal_handler):
self.old_signal_handler(signum, frame)
elif self.old_signal_handler == signal.SIG_DFL:
sys.exit(0)
示例4: unsubscribe
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def unsubscribe(self):
"""Unsubscribe self.handlers from signals."""
for signum, handler in self._previous_handlers.items():
signame = self.signals[signum]
if handler is None:
self.bus.log('Restoring %s handler to SIG_DFL.' % signame)
handler = _signal.SIG_DFL
else:
self.bus.log('Restoring %s handler %r.' % (signame, handler))
try:
our_handler = _signal.signal(signum, handler)
if our_handler is None:
self.bus.log('Restored old %s handler %r, but our '
'handler was not registered.' %
(signame, handler), level=30)
except ValueError:
self.bus.log('Unable to restore %s handler %r.' %
(signame, handler), level=40, traceback=True)
示例5: cli
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def cli(ctx):
"""\b
Welcome to the Wio Command line utility!
https://github.com/Seeed-Studio/wio-cli
For more information Run: wio <command_name> --help
"""
ctx.obj = Wio()
cur_dir = os.path.abspath(os.path.expanduser("~/.wio"))
if not os.path.exists(cur_dir):
text = {"email":"", "token":""}
os.mkdir(cur_dir)
open("%s/config.json"%cur_dir,"w").write(json.dumps(text))
db_file_path = '%s/config.json' % cur_dir
config = json.load(open(db_file_path))
ctx.obj.config = config
signal.signal(signal.SIGINT, sigint_handler)
if not verify:
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
示例6: __init__
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def __init__(self, freq = 100.0):
EventDispatcher2.state_lock.acquire()
if EventDispatcher2.ed_inum != 0:
EventDispatcher2.state_lock.release()
raise StdException('BZZZT, EventDispatcher2 has to be singleton!')
EventDispatcher2.ed_inum = 1
EventDispatcher2.state_lock.release()
self.tcbs_lock = Lock()
self.tlisteners = []
self.slisteners = []
self.signals_pending = []
self.last_ts = MonoTime()
self.my_ident = get_ident()
self.elp = ElPeriodic(freq)
self.elp.CFT_enable(signal.SIGURG)
self.bands = [(freq, 0),]
示例7: test_multiprocessing
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def test_multiprocessing(app):
"""Tests that the number of children we produce is correct"""
# Selects a number at random so we can spot check
num_workers = random.choice(range(2, multiprocessing.cpu_count() * 2 + 1))
process_list = set()
def stop_on_alarm(*args):
for process in multiprocessing.active_children():
process_list.add(process.pid)
process.terminate()
signal.signal(signal.SIGALRM, stop_on_alarm)
signal.alarm(3)
app.run(HOST, PORT, workers=num_workers)
assert len(process_list) == num_workers
示例8: ctrlc_workaround_for_windows
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def ctrlc_workaround_for_windows(app):
async def stay_active(app):
"""Asyncio wakeups to allow receiving SIGINT in Python"""
while not die:
# If someone else stopped the app, just exit
if app.is_stopping:
return
# Windows Python blocks signal handlers while the event loop is
# waiting for I/O. Frequent wakeups keep interrupts flowing.
await asyncio.sleep(0.1)
# Can't be called from signal handler, so call it from here
app.stop()
def ctrlc_handler(sig, frame):
nonlocal die
if die:
raise KeyboardInterrupt("Non-graceful Ctrl+C")
die = True
die = False
signal.signal(signal.SIGINT, ctrlc_handler)
app.add_task(stay_active)
示例9: __init__
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
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
示例10: testInterruptCaught
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def testInterruptCaught(self):
default_handler = signal.getsignal(signal.SIGINT)
result = unittest.TestResult()
unittest.installHandler()
unittest.registerResult(result)
self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)
def test(result):
pid = os.getpid()
os.kill(pid, signal.SIGINT)
result.breakCaught = True
self.assertTrue(result.shouldStop)
try:
test(result)
except KeyboardInterrupt:
self.fail("KeyboardInterrupt not handled")
self.assertTrue(result.breakCaught)
示例11: testSecondInterrupt
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def testSecondInterrupt(self):
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)
示例12: testTwoResults
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def testTwoResults(self):
unittest.installHandler()
result = unittest.TestResult()
unittest.registerResult(result)
new_handler = signal.getsignal(signal.SIGINT)
result2 = unittest.TestResult()
unittest.registerResult(result2)
self.assertEqual(signal.getsignal(signal.SIGINT), new_handler)
result3 = unittest.TestResult()
def test(result):
pid = os.getpid()
os.kill(pid, signal.SIGINT)
try:
test(result)
except KeyboardInterrupt:
self.fail("KeyboardInterrupt not handled")
self.assertTrue(result.shouldStop)
self.assertTrue(result2.shouldStop)
self.assertFalse(result3.shouldStop)
示例13: testHandlerReplacedButCalled
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def testHandlerReplacedButCalled(self):
# 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")
示例14: enable_death_signal
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def enable_death_signal(_warn=True):
"""
Set the "death signal" of the current process, so that
the current process will be cleaned with guarantee
in case the parent dies accidentally.
"""
if platform.system() != 'Linux':
return
try:
import prctl # pip install python-prctl
except ImportError:
if _warn:
log_once('"import prctl" failed! Install python-prctl so that processes can be cleaned with guarantee.',
'warn')
return
else:
assert hasattr(prctl, 'set_pdeathsig'), \
"prctl.set_pdeathsig does not exist! Note that you need to install 'python-prctl' instead of 'prctl'."
# is SIGHUP a good choice?
prctl.set_pdeathsig(signal.SIGHUP)
示例15: start_proc_mask_signal
# 需要导入模块: import signal [as 别名]
# 或者: from signal import signal [as 别名]
def start_proc_mask_signal(proc):
"""
Start process(es) with SIGINT ignored.
Args:
proc: (mp.Process or list)
Note:
The signal mask is only applied when called from main thread.
"""
if not isinstance(proc, list):
proc = [proc]
with mask_sigint():
for p in proc:
if isinstance(p, mp.Process):
if sys.version_info < (3, 4) or mp.get_start_method() == 'fork':
log_once("""
Starting a process with 'fork' method is efficient but not safe and may cause deadlock or crash.
Use 'forkserver' or 'spawn' method instead if you run into such issues.
See https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods on how to set them.
""".replace("\n", ""),
'warn') # noqa
p.start()