本文整理匯總了Python中_thread.interrupt_main方法的典型用法代碼示例。如果您正苦於以下問題:Python _thread.interrupt_main方法的具體用法?Python _thread.interrupt_main怎麽用?Python _thread.interrupt_main使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類_thread
的用法示例。
在下文中一共展示了_thread.interrupt_main方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: pipe_fopen
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def pipe_fopen(command, mode, background=True):
if mode not in ["rb", "r"]:
raise RuntimeError("Now only support input from pipe")
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
def background_command_waiter(command, p):
p.wait()
if p.returncode != 0:
warnings.warn("Command \"{0}\" exited with status {1}".format(
command, p.returncode))
_thread.interrupt_main()
if background:
thread = threading.Thread(target=background_command_waiter,
args=(command, p))
# exits abnormally if main thread is terminated .
thread.daemon = True
thread.start()
else:
background_command_waiter(command, p)
return p.stdout
示例2: _schedule_batch
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def _schedule_batch(self, client_ids, fetches):
"""Schedules a single batch for execution."""
with timer_counter(self.counters, 'executor-inference'):
try:
ret = self.session.run(
fetches, {
self.model.input_seed: self.input_seed,
self.model.input_patches: self.input_image})
except Exception as e: # pylint:disable=broad-except
logging.exception(e)
# If calling TF didn't work (faulty hardware, misconfiguration, etc),
# we want to terminate the whole program.
thread.interrupt_main()
raise e
with timer_counter(self.counters, 'executor-output'):
with self._lock:
for i, client_id in enumerate(client_ids):
try:
self.outputs[client_id].put(
{k: v[i, ...] for k, v in ret.items()})
except KeyError:
# This could happen if a client unregistered itself
# while inference was running.
pass
示例3: parse_loop
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def parse_loop(parse: Callable[[], List[Metric]], storage: Storage,
append_service_level_metrics_func: Callable[[List[Metric]], None]):
"""
Runs parsing and kafka storage in loop. parse_loop.last_valid_metrics list is accessed
by the HTTP server GET request handler.
"""
parse_loop.metrics = []
parse_loop.last_valid_metrics = []
while True:
try:
parse_loop.metrics = parse()
# parse() can return an empty list, so we store new values for kafka and http server
# only when there are new metrics to store
if parse_loop.metrics:
append_service_level_metrics_func(metrics=parse_loop.metrics)
for metric in parse_loop.metrics:
log.debug("Found metric: {}".format(metric))
parse_loop.last_valid_metrics = parse_loop.metrics.copy()
if storage is not None:
store_with_retry(storage, parse_loop.last_valid_metrics)
except BaseException:
_thread.interrupt_main()
raise
示例4: run
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def run(self):
exists = os.path.exists
mtime = lambda path: os.stat(path).st_mtime
files = dict()
for module in list(sys.modules.values()):
path = getattr(module, '__file__', '')
if path[-4:] in ('.pyo', '.pyc'): path = path[:-1]
if path and exists(path): files[path] = mtime(path)
while not self.status:
if not exists(self.lockfile)\
or mtime(self.lockfile) < time.time() - self.interval - 5:
self.status = 'error'
thread.interrupt_main()
for path, lmtime in list(files.items()):
if not exists(path) or mtime(path) > lmtime:
self.status = 'reload'
thread.interrupt_main()
break
time.sleep(self.interval)
示例5: exit_after
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def exit_after(s):
"""
Use as decorator to exit process if
function takes longer than s seconds.
Direct call is available via exit_after(TIMEOUT_IN_S)(fce)(args).
Inspired by https://stackoverflow.com/a/31667005
"""
def outer(fn):
def inner(*args, **kwargs):
timer = threading.Timer(s, thread.interrupt_main)
timer.start()
try:
result = fn(*args, **kwargs)
except KeyboardInterrupt:
raise TimeoutError("Function '{}' hit the timeout ({}s).".format(fn.__name__, s))
finally:
timer.cancel()
return result
return inner
return outer
示例6: run
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def run(self):
exists = os.path.exists
mtime = lambda p: os.stat(p).st_mtime
files = dict()
for module in list(sys.modules.values()):
path = getattr(module, '__file__', '')
if path[-4:] in ('.pyo', '.pyc'): path = path[:-1]
if path and exists(path): files[path] = mtime(path)
while not self.status:
if not exists(self.lockfile)\
or mtime(self.lockfile) < time.time() - self.interval - 5:
self.status = 'error'
thread.interrupt_main()
for path, lmtime in list(files.items()):
if not exists(path) or mtime(path) > lmtime:
self.status = 'reload'
thread.interrupt_main()
break
time.sleep(self.interval)
示例7: write_rtt
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def write_rtt(jlink):
"""Writes kayboard input to JLink RTT buffer #0.
This method is a loop that blocks waiting on stdin. When enter is pressed,
LF and NUL bytes are added to the input and transmitted as a byte list.
If the JLink is disconnected, it will exit gracefully. If any other
exceptions are raised, they will be caught and re-raised after interrupting
the main thread.
Args:
jlink (pylink.JLink): The JLink to write to.
Raises:
Exception on error.
"""
try:
while jlink.connected():
bytes = list(bytearray(input(), "utf-8") + b"\x0A\x00")
bytes_written = jlink.rtt_write(0, bytes)
except Exception:
print("IO write thread exception, exiting...")
thread.interrupt_main()
raise
示例8: recv_bytes
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def recv_bytes(self, connection):
"""
Given a socket connection, receive up to 2048 bytes
from its buffer and return that data as a bytes object.
Returns an empty bytes object if there is no data to receive.
"""
try:
bytes_message = connection.recv(2048)
except BlockingIOError:
# Non-blocking socket couldn't immediately receive.
return None
except ConnectionResetError:
self._print_message('Connection was reset.')
self.connection.close()
_thread.interrupt_main()
return bytes_message
示例9: _terminate_execution
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def _terminate_execution(self):
# called from receiverthread
self._trace("shutting down execution pool")
self._execpool.trigger_shutdown()
if not self._execpool.waitall(5.0):
self._trace("execution ongoing after 5 secs," " trying interrupt_main")
# We try hard to terminate execution based on the assumption
# that there is only one gateway object running per-process.
if sys.platform != "win32":
self._trace("sending ourselves a SIGINT")
os.kill(os.getpid(), 2) # send ourselves a SIGINT
elif interrupt_main is not None:
self._trace("calling interrupt_main()")
interrupt_main()
if not self._execpool.waitall(10.0):
self._trace(
"execution did not finish in another 10 secs, " "calling os._exit()"
)
os._exit(1)
示例10: default_handle_exception_interrupt_main_thread
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def default_handle_exception_interrupt_main_thread(func):
"""
:param func: any function. usually run in another thread.
If some exception occurs, it will interrupt the main thread (send KeyboardInterrupt to the main thread).
If this is run in the main thread itself, it will raise SystemExit(1).
:return: function func wrapped
"""
import sys
import _thread
import threading
def wrapped_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
logging.error("Exception in thread %r:" % threading.current_thread())
sys.excepthook(*sys.exc_info())
if threading.current_thread() is not threading.main_thread():
_thread.interrupt_main()
raise SystemExit(1)
return wrapped_func
示例11: run
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def run(self):
exists = os.path.exists
mtime = lambda p: os.stat(p).st_mtime
files = dict()
for module in list(sys.modules.values()):
path = getattr(module, '__file__', '') or ''
if path[-4:] in ('.pyo', '.pyc'): path = path[:-1]
if path and exists(path): files[path] = mtime(path)
while not self.status:
if not exists(self.lockfile)\
or mtime(self.lockfile) < time.time() - self.interval - 5:
self.status = 'error'
thread.interrupt_main()
for path, lmtime in list(files.items()):
if not exists(path) or mtime(path) > lmtime:
self.status = 'reload'
thread.interrupt_main()
break
time.sleep(self.interval)
示例12: run
# 需要導入模塊: import _thread [as 別名]
# 或者: from _thread import interrupt_main [as 別名]
def run(self):
if self.timeout > 0:
time.sleep (self.timeout)
thread.interrupt_main()