本文整理汇总了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()