本文整理匯總了Python中signal.default_int_handler方法的典型用法代碼示例。如果您正苦於以下問題:Python signal.default_int_handler方法的具體用法?Python signal.default_int_handler怎麽用?Python signal.default_int_handler使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類signal
的用法示例。
在下文中一共展示了signal.default_int_handler方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [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
示例2: _shutdown_on_exception
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
def _shutdown_on_exception(app: skein.ApplicationClient):
# Ensure SIGINT is not masked to enable kill on C-c.
import signal
signal.signal(signal.SIGINT, signal.default_int_handler)
try:
yield
except (KeyboardInterrupt, SystemExit):
with suppress(SkeinError):
app.shutdown(FinalStatus.KILLED)
logger.error("Application killed on user request")
except Exception:
with suppress(SkeinError):
app.shutdown(FinalStatus.FAILED)
logger.exception("Application shutdown due to an exception")
raise
示例3: _downloadLocalFile
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
def _downloadLocalFile(self, key, suffix):
# Set default signal handler so that KeyboardInterrupt is raised.
# Needed to gracefully handle ctrl+c.
signal.signal(signal.SIGINT, signal.default_int_handler)
try:
with self._openDownloadFile(key, suffix) as (name, fileobj):
ret = readFileOrHandle(name, fileobj)
return (ret, None, None)
except ArtifactNotFoundError:
return (None, "not found", WARNING)
except ArtifactDownloadError as e:
return (None, e.reason, WARNING)
except BuildError as e:
raise
except OSError as e:
raise BuildError("Cannot download file: " + str(e))
finally:
# Restore signals to default so that Ctrl+C kills process. Needed
# to prevent ugly backtraces when user presses ctrl+c.
signal.signal(signal.SIGINT, signal.SIG_DFL)
示例4: _uploadPackage
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
def _uploadPackage(self, buildId, suffix, audit, content):
# Set default signal handler so that KeyboardInterrupt is raised.
# Needed to gracefully handle ctrl+c.
signal.signal(signal.SIGINT, signal.default_int_handler)
try:
with self._openUploadFile(buildId, suffix) as (name, fileobj):
pax = { 'bob-archive-vsn' : "1" }
with gzip.open(name or fileobj, 'wb', 6) as gzf:
with tarfile.open(name, "w", fileobj=gzf,
format=tarfile.PAX_FORMAT, pax_headers=pax) as tar:
tar.add(audit, "meta/" + os.path.basename(audit))
tar.add(content, arcname="content")
except ArtifactExistsError:
return ("skipped ({} exists in archive)".format(content), SKIPPED)
except (ArtifactUploadError, tarfile.TarError, OSError) as e:
if self.__ignoreErrors:
return ("error ("+str(e)+")", ERROR)
else:
raise BuildError("Cannot upload artifact: " + str(e))
finally:
# Restore signals to default so that Ctrl+C kills process. Needed
# to prevent ugly backtraces when user presses ctrl+c.
signal.signal(signal.SIGINT, signal.SIG_DFL)
return ("ok", EXECUTED)
示例5: _uploadLocalFile
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
def _uploadLocalFile(self, key, suffix, content):
# Set default signal handler so that KeyboardInterrupt is raised.
# Needed to gracefully handle ctrl+c.
signal.signal(signal.SIGINT, signal.default_int_handler)
try:
with self._openUploadFile(key, suffix) as (name, fileobj):
writeFileOrHandle(name, fileobj, content)
except ArtifactExistsError:
return ("skipped (exists in archive)", SKIPPED)
except (ArtifactUploadError, OSError) as e:
if self.__ignoreErrors:
return ("error ("+str(e)+")", ERROR)
else:
raise BuildError("Cannot upload file: " + str(e))
finally:
# Restore signals to default so that Ctrl+C kills process. Needed
# to prevent ugly backtraces when user presses ctrl+c.
signal.signal(signal.SIGINT, signal.SIG_DFL)
return ("ok", EXECUTED)
示例6: __init__
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
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
示例7: MakeValidSysOuts
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
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
示例8: test_signal_signal
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
def test_signal_signal(self):
WORKING_CASES = SUPPORTED_SIGNALS + [6]
WEIRD_CASES = {
6: None,
2: signal.default_int_handler}
for x in WORKING_CASES:
#Ideal handler signature
def a(signum, frame):
return x
ret_val = signal.signal(x, a)
if x not in WEIRD_CASES.keys():
self.assertEqual(ret_val, signal.SIG_DFL)
else:
self.assertEqual(ret_val, WEIRD_CASES[x])
self.assertEqual(a, signal.getsignal(x))
#Strange handler signatures
class KNew(object):
def __call__(self, *args, **kwargs):
pass
a = KNew()
ret_val = signal.signal(signal.SIGBREAK, a)
self.assertEqual(a, signal.getsignal(signal.SIGBREAK))
示例9: _handleSignals
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
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)
示例10: handle_error
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
def handle_error(index_name, keep=False, timeout=None):
'''
Handle errors while indexing.
In case of error, properly log it, remove the index and exit.
If `keep` is `True`, index is not deleted.
'''
# Handle keyboard interrupt
signal.signal(signal.SIGINT, signal.default_int_handler)
signal.signal(signal.SIGTERM, signal.default_int_handler)
has_error = False
try:
yield
except KeyboardInterrupt:
print('') # Proper warning message under the "^C" display
log.warning('Interrupted by signal')
has_error = True
except Exception as e:
log.error(e)
has_error = True
if has_error:
if not keep:
log.info('Removing index %s', index_name)
es.indices.delete(index=index_name, request_timeout=timeout)
sys.exit(-1)
示例11: handle_error
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
def handle_error(prefix, to_delete=None):
'''
Handle errors while loading.
In case of error, properly log it, remove the temporary files and collections and exit.
If `to_delete` is given a collection, it will be deleted deleted.
'''
# Handle keyboard interrupt
signal.signal(signal.SIGINT, signal.default_int_handler)
signal.signal(signal.SIGTERM, signal.default_int_handler)
try:
yield
except KeyboardInterrupt:
print('') # Proper warning message under the "^C" display
log.warning('Interrupted by signal')
except Exception as e:
log.error(e)
else:
return # Nothing to do in case of success
cleanup(prefix)
if to_delete:
log.info('Removing temporary collection %s', to_delete._get_collection_name())
to_delete.drop_collection()
sys.exit(-1)
示例12: _kill_process
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
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
示例13: _run
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
def _run(self) -> None:
signal.signal(signal.SIGINT, signal.default_int_handler)
signal.signal(signal.SIGTERM, signal.default_int_handler)
try:
self.log.debug("Running startup actions...")
start_ts = time()
self.loop.run_until_complete(self.start())
end_ts = time()
self.log.info(f"Startup actions complete in {round(end_ts - start_ts, 2)} seconds, "
"now running forever")
self._stop_task = self.loop.create_future()
self.loop.run_until_complete(self._stop_task)
self.log.debug("manual_stop() called, stopping...")
except KeyboardInterrupt:
self.log.debug("Interrupt received, stopping...")
except Exception:
self.log.critical("Unexpected error in main event loop", exc_info=True)
sys.exit(2)
self.prepare_stop()
self.loop.run_until_complete(self.stop())
self.prepare_shutdown()
self.log.info("Everything stopped, shutting down")
sys.exit(0)
示例14: test_signal_signal
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
def test_signal_signal(self):
WORKING_CASES = SUPPORTED_SIGNALS + [6]
WEIRD_CASES = {
6: None,
2: signal.default_int_handler}
for x in WORKING_CASES:
#Ideal handler signature
def a(signum, frame):
return x
ret_val = signal.signal(x, a)
if x not in WEIRD_CASES.keys():
self.assertEqual(ret_val, signal.SIG_DFL)
else:
self.assertEqual(ret_val, WEIRD_CASES[x])
self.assertEqual(a, signal.getsignal(x))
#Strange handler signatures
class KNew(object):
def __call__(self, *args, **kwargs):
pass
a = KNew()
ret_val = signal.signal(signal.SIGBREAK, a)
self.assertEqual(a, signal.getsignal(signal.SIGBREAK))
示例15: waitForInterrupt
# 需要導入模塊: import signal [as 別名]
# 或者: from signal import default_int_handler [as 別名]
def waitForInterrupt():
if signal.getsignal(signal.SIGINT) != signal.default_int_handler:
raise RuntimeError("Already waiting")
d = Deferred()
def fire(*ignored):
global interrupted
signal.signal(signal.SIGINT, signal.default_int_handler)
now = time.time()
if now - interrupted < 4:
reactor.callFromThread(lambda: d.errback(Failure(Stop())))
else:
interrupted = now
reactor.callFromThread(d.callback, None)
signal.signal(signal.SIGINT, fire)
return d