def handle_error(self, request, client_address): """Override RPCServer method for IDLE Interrupt the MainThread and exit server if link is dropped. """ global quitting try: raise except SystemExit: raise except EOFError: global exit_now exit_now = True thread.interrupt_main() except: erf = sys.__stderr__ print('\n' + '-'*40, file=erf) print('Unhandled server exception!', file=erf) print('Thread: %s' % threading.current_thread().name, file=erf) print('Client Address: ', client_address, file=erf) print('Request: ', repr(request), file=erf) traceback.print_exc(file=erf) print('\n*** Unrecoverable, server exiting!', file=erf) print('-'*40, file=erf) quitting = True thread.interrupt_main()
def connect_to_server(): try: srv_conn_socket = socket.socket() srv_conn_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)#Addresse wieder verwenden srv_conn_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)#Port wieder verwenden srv_conn_socket.bind((ip, port))#IP + Port "zusammenfuehren" except: print ("Could not set up socket. (SRV connection)") sys.exit(1) #srv_conn_socket.bind('', int(sys.argv[3])) while(srv_conn_socket.connect_ex((sys.argv[4], int(sys.argv[2])))):#SYN Packets an Server senden pass print("connected to server!") #daten von server bekommen/anfordern/senden srv_conn_socket.send(b'LR') #Daten eintragen und liste vom server bekommen print ("LR sent") #srv_conn_socket.send("R") #Daten vom server holen #srv_conn_socket.send("L") #Daten in liste eintragen data= srv_conn_socket.recv(1024) #daten von server erhalten print ("recived...") utf_data = data.decode('utf-8') print(utf_data) thread.interrupt_main()
def run(self): """Run the rpc thread.""" self._started.set() self._running = True try: while True: msg = self._queue.get() try: # If we received a null value, then we're supposed to shut # down. if msg is _NULL: sys.stdout.flush() break self._process(msg) finally: # ... and let the queue know we finished. self._queue.task_done() except KeyboardInterrupt: # let the main thread know we got a SIGINT import _thread _thread.interrupt_main() raise except BaseException as err: raise finally: self._running = False
def handle_wrap(self, msg, args): if msg in ("Call", "Doc"): path = args["Macro"].rsplit(".", 1) if len(path)==1: path.insert(0, DEF_MODULE) if path[0] in macro_tree and path[1] in macro_tree[path[0]]: macro = getattr(modules[path[0]], path[1], None) else: macro = None if not macro: return "SERVER_NO_MACRO" elif msg == "Doc": print("Help on '%s' requested"%args["Macro"]) return macro.__doc__ or "" else: #Caller must 'Test' if server is 'OK' before this print("Macro '%s' called "%path[1]) invoker.invoke(app().form.startMacro, macro, args["Workbook"]) return "OK" elif msg == "Request": print("Macro list requested") return "|".join(getMacroList(args["Application"])) elif msg == "Test": print("Connection checked") with run_lock: return "Busy" if not run_lock._value else "OK" elif msg == "Interrupt": print("Request to interrupt macro") with run_lock: #FIXME: It's possible to make several requests before macro is interrupted. Is it ok? if not run_lock._value: _thread.interrupt_main() else: return "Not busy" return "OK" else: print("Unknown message") return "Unknown"
def stdin_listener(): with stdout_lock: print("Enter quit or exit to shut down the server and exit.") while True: kybd_in = input() kybd_in = shlex.split(kybd_in) if kybd_in[0] == "quit" or kybd_in[0] == "exit": with stdout_lock: print("***Received quit signal from stdin. Exiting application...") interrupt_main() elif kybd_in[0] == "query": if len(kybd_in) == 2: print_database_query(database_query("localhost", kybd_in[1] + " ")) else: with stdout_lock: print("***Invalid query.") elif kybd_in[0] == "reset": reset_server() with stdout_lock: print("\t-->Server reset complete!") elif kybd_in[0] == "status": connected_clients = get_db_clients() with stdout_lock: print("\t-->{} connected clients.".format(len(connected_clients))) elif kybd_in[0] == "verbose": global verbose if verbose: verbose = False else: verbose = True else: with stdout_lock: print("***Invalid Input!")
def import_files(self, settings_name): """Import saved settings from file. Args: settings_name (str): The id of the saved settings. """ print('importing in classifier') try: export_path = Classifier.\ _get_file_path(self.files[EXPORT_SAVING_FILE], settings_name) file_with_export = open(export_path, 'rb') box = pickle.load(file_with_export) file_with_export.close() except FileNotFoundError: print("name of settings not found in classifier database") _thread.interrupt_main() sys.exit(1) symbol_list = box.pop(0) file_with_symbols = \ open(self.files[SYMBOL_LIST_FILE], 'wb') pickle.dump(symbol_list, file_with_symbols) file_with_symbols.close() inactive_symbols = box.pop(0) file_with_inactive_symbols = \ open(self.files[INACTIVE_SYMBOLS_FILE], 'wb') pickle.dump(inactive_symbols, file_with_inactive_symbols) file_with_inactive_symbols.close() general_model = box.pop(0) file_with_model = \ open(Classifier._get_file_path(self.files[MODEL_FILE], ""), 'wb') pickle.dump(general_model, file_with_model) file_with_model.close() for symbol in symbol_list: learning_model = box.pop(0) file_with_model = \ open(Classifier._get_file_path(self.files[MODEL_FILE], symbol), 'wb') pickle.dump(learning_model, file_with_model) file_with_model.close() tolerance_distance = box.pop(0) tolerance_distance_path = Classifier._get_file_path( self.files[DISTANCE_TOLERANCE_FILE], symbol) file_with_tolerance_distance = \ open(tolerance_distance_path, 'w') file_with_tolerance_distance.write("%.16f\n" % (tolerance_distance)) file_with_tolerance_distance.close() training_set = box.pop(0) file_with_training_path = \ Classifier._get_file_path(self.files[TRAINING_SET_FILE], symbol) file_with_training = \ open(file_with_training_path, 'wb') pickle.dump(training_set, file_with_training) file_with_training.close()
def reload_checker(interval): while True: changed = False files = {} 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] = os.stat(path).st_mtime while not changed: for path, last_modified in files.items(): if not exists(path): print('\n> Reloading due to file removal: {}'.format(path)) changed = True elif os.stat(path).st_mtime > last_modified: print('\n> Reloading due to file change: {}'.format(path)) changed = True if changed: reload_checker.reloading = True thread.interrupt_main() time.sleep(5) break time.sleep(interval)
def run(self): # If parent shuts down (and we are adopted by a different parent # process), we should shut down. while (os.getppid() == self.parent_pid): time.sleep(0.5) interrupt_main()
def handler(sig): try: import _thread except ImportError: import thread as _thread _thread.interrupt_main() return 1
def f(): for x in range(40): if waiting: _thread.interrupt_main() return print("tock...", x) # <-force the GIL to be released, as time.sleep(0.1) # time.sleep doesn't do non-translated
def run(self): try_interval = 1 while True: try: try_interval *= 2 with self.capp.connection() as conn: recv = EventReceiver(conn, handlers={"*": self.on_event}, app=self.capp) try_interval = 1 recv.capture(limit=None, timeout=None, wakeup=True) except (KeyboardInterrupt, SystemExit): try: import _thread as thread except ImportError: import thread thread.interrupt_main() except Exception as e: logger.error("Failed to capture events: '%s', " "trying again in %s seconds.", e, try_interval) logger.debug(e, exc_info=True) time.sleep(try_interval)
def bind_symbol_with_command(symbol, command='touch', command_arguments=None, stop_when_overwriting=False, stop_when_new=False): """Bind the symbol's name with the provided command. The default command is touch and the command_arguments will be set to '/tmp/created_by_' + symbol. Args: symbol (str): The symbol's name. command (str): The shell command to be bound with the symbol. command_arguments (str): The arguments for the command. """ global _USER_DEFINED_COMMANDS _check_and_load_commands() if stop_when_overwriting and symbol in _USER_DEFINED_COMMANDS: print("symbol", symbol, 'is already in database') _thread.interrupt_main() sys.exit(1) if stop_when_new and symbol not in _USER_DEFINED_COMMANDS: print("symbol", symbol, 'is not present in database') _thread.interrupt_main() sys.exit(1) if command == 'touch' and command_arguments is None: command_arguments = '/tmp/created_by_' + symbol _USER_DEFINED_COMMANDS[symbol] = Command(command, command_arguments) if not os.path.exists(DATA_PATH): os.makedirs(DATA_PATH) with open(DATA_PATH + USER_DEFINED_COMMANDS_FILE, 'wb') as handle: pickle.dump(_USER_DEFINED_COMMANDS, handle) print('symbol ', symbol, 'has been binded with command')
def run(self): log.critical("InputPollThread.run() start") try: self._run() except KeyboardInterrupt: _thread.interrupt_main() log.critical("InputPollThread.run() ends, because CPU not alive anymore.")
def run(self): try: self._run() except: self.cpu.running = False _thread.interrupt_main() raise
def run(self): """ Run the poll loop. This method never returns. """ from _subprocess import WAIT_OBJECT_0, INFINITE # Build the list of handle to listen on. handles = [] if self.interrupt_handle: handles.append(self.interrupt_handle) if self.parent_handle: handles.append(self.parent_handle) # Listen forever. while True: result = ctypes.windll.kernel32.WaitForMultipleObjects( len(handles), # nCount (ctypes.c_int * len(handles))(*handles), # lpHandles False, # bWaitAll INFINITE) # dwMilliseconds if WAIT_OBJECT_0 <= result < len(handles): handle = handles[result - WAIT_OBJECT_0] if handle == self.interrupt_handle: interrupt_main() elif handle == self.parent_handle: os._exit(1)
def handler(sig): try: import _thread except ImportError: import thread as _thread _thread.interrupt_main() return 1 # do not execute any other handlers.
def send_bytes(self, connection, bytes_message): try: connection.sendall(bytes_message) except ConnectionResetError: self._print_message('Connection was reset.') self.connection.close() _thread.interrupt_main() sys.exit(1)
def run_with_except_hook(*args, **kw): try: run_old(*args, **kw) except (KeyboardInterrupt, SystemExit): raise except: sys.excepthook(*sys.exc_info()) _thread.interrupt_main() # 保证主线程退出
def on_event(self, m): if m.get('id') != None: self.last_log_id = m.get('id') try: self.on_event_cb(m) except Exception as e: _logger.exception("Unexpected exception from event callback.") _thread.interrupt_main()
def server(listener = listener): client = listener.accept()[0] listener.close() conn = connect_stream(SocketStream(client), service = remote_service, config = remote_config) try: conn.serve_all() except KeyboardInterrupt: _thread.interrupt_main()
def call(self, event): if event[0] != 4: return if event[6].partition(' ')[0] == '/status' and event[3] < 2000000000: self.bot.vkapi.messages.send(message='Я жив ' + str(datetime.datetime.now() - self.start_time), peer_id=event[3]) elif event[6].partition(' ')[0] == '/kill' and event[3] in self.config["bot"]["admins"]: print("Killed by", event[3]) self.bot.vkapi.messages.send(message='Умираю', peer_id=event[3]) _thread.interrupt_main()
def do_something(): """ do_something """ time0 = time.time() while (time.time() - time0) < 30 and not G_EVENT.isSet(): time.sleep(0.5) _thread.interrupt_main()
def subthread(): try: time.sleep(0.5) with __pypy__.thread.signals_enabled: _thread.interrupt_main() except BaseException as e: interrupted.append(e) finally: lock.release()
def __io_thread_func(self): # wrapper around the actual io loop func for # exception handling try: self.__io_loop() except Exception: #IGNORE:W0703 print("exception in conductor I/O loop thread") traceback.print_exc() _thread.interrupt_main()
def run(self): """ Sleep for `.secs` seconds, then, if the alarm has not been cancelled, interrupt the main thread. """ time.sleep(self.secs) if self.do_interrupt: _thread.interrupt_main()
def read(self, size): buf = self.socket.read(size) if not buf: print('Connection closed.', file=self.ostream) _thread.interrupt_main() raise ClientClosedError() return buf
def _listener(): while True: command = _messages_from_interrupter.get() if command['type'] == 'command': if command['command'] == 'exit': break elif command['command'] == 'interrupt_main_thread': if status.is_busy(): thread.interrupt_main()
def _get_from_port(self): try: return self._port.read(4096) except OSError as ex: self._resume = False print(str(ex), file=stderr) interrupt_main() except Exception as ex: print(str(ex), file=stderr) return array('B')
def interrupt_and_finish(cls): """Interrupt the main thread and exit. Clean the C language data structures. Exit thread with the exit code of 1. """ cls.clean() _thread.interrupt_main() sys.exit(1)
def run(self): log.critical(" *** MachineThread.run() start *** ") try: self.machine.run() except Exception as err: log.critical("MachineThread exception: %s", err) print_exc_plus() _thread.interrupt_main() raise log.critical(" *** MachineThread.run() stopped. *** ")
def interrupt_the_server(self): if interruptable: thread.interrupt_main()
def wait(): start = time.time() while len(patched_redis.data['events']) < 4 and time.time() - start < 1: time.sleep(1e-2) interrupt_main()
def exit(self): if not self.exiting: self.payments_queue.put([self.create_exit_payment()]) self.exiting = True _thread.interrupt_main()
def _die(self, e): logger.critical(e) _thread.interrupt_main() sys.exit(e)
def quit_function(fn_name): # print to stderr, unbuffered in Python 2. print('{0} took too long'.format(fn_name), file=sys.stderr) sys.stderr.flush() # Python 3 stderr is likely buffered. _thread.interrupt_main() # raises KeyboardInterrupt
def wait(secs): for n in range(timeout_secs): time.sleep(1) if signal_finished: break else: _thread.interrupt_main()
pyautogui.click() while True: docked_box = pyautogui.locateOnScreen( '\\data\\DockedBox.png', region=(977, 642, 147, 75), confidence=0.9) open_box = pyautogui.locateOnScreen( '\\data\\TakeAll.png', region=(1065, 674, 87, 39), confidence=0.9) server_down = pyautogui.locateOnScreen( '\\data\\server.png', region=(742, 452, 410, 65),confidence=0.9) if docked_box: print('Box is docked') pyautogui.moveTo(1214, 668) pyautogui.click() # open box pyautogui.moveTo(1107, 695) time.sleep(2) pyautogui.click() # clicks take all _thread.interrupt_main() else: pass if open_box: print('Box is open') pyautogui.moveTo(1107, 695) time.sleep(0.1) pyautogui.click() # clicks take all time.sleep(0.5) _thread.interrupt_main() else: pass if not (docked_box and open_box): print("Server down")
def EOFhook(self): """Override SocketIO method - terminate wait on callback and exit thread""" global quitting quitting = True thread.interrupt_main()
def decode_interrupthook(self): """interrupt awakened thread""" global quitting quitting = True thread.interrupt_main()
def receive_dashboard_commands(self): self.dashboard_socket.listen() while True: connection, addr = self.dashboard_socket.accept() connection.settimeout(5) try: data = connection.recv(1) if data: command = struct.unpack("<1B", data)[0] if command == CommunicationsManager.STOP_COMMAND: connection.close() with self.stop_lock: print_message("Stopping experiment") self.broadcast_groups = [] #TODO Stop is now useless, probably best to just replace with shutdown elif command == CommunicationsManager.SHUTDOWN_COMMAND: print_message("Received Shutdown command") msg = "packets: recv " + str( self.received) + ", prod " + str(self.produced) print_identified(self.graph, msg) connection.send( struct.pack("<3Q", self.produced, 50, self.received)) ack = connection.recv(1) if len(ack) != 1: print_error("Bad ACK len:" + str(len(ack))) connection.close() continue if struct.unpack("<1B", ack)[0] != CommunicationsManager.ACK: print_error("Bad ACK, not and ACK" + str(struct.unpack("<1B", ack))) connection.close() continue connection.close() with self.stop_lock: # self.process_pool.terminate() # self.process_pool.join() self.dashboard_socket.close() for s in broadcast_sockets: s.close() # self.sock.close() PathEmulation.tearDown() print_identified(self.graph, "Shutting down") sys.stdout.flush() sys.stderr.flush() stop_experiment() interrupt_main() return elif command == CommunicationsManager.READY_COMMAND: connection.send( struct.pack("<1B", CommunicationsManager.ACK)) connection.close() elif command == CommunicationsManager.START_COMMAND: connection.close() print_message("Starting Experiment!") self.scheduler.start() except OSError as e: continue # Connection timed out (most likely)
def run(self): time.sleep(2) _thread.interrupt_main()
def _quit(): print("quitting") _thread.interrupt_main()
def run(self): try: super().run() except Exception: # pragma: no cover _thread.interrupt_main() raise
def timeout_func(): #env.logger.error('Timed out for operation {}'.format(msg)) _thread.interrupt_main()
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()
def run(self): if self.to_sleep: time.sleep(self.to_sleep) _thread.interrupt_main()
def quit_function(fn_name): sys.stderr.flush() thread.interrupt_main() # raises KeyboardInterrupt
def process_worker_ch(tenant, worker_ch, actor_id, worker_id, actor_ch, ag_client): """ Target for a thread to listen on the worker channel for a message to stop processing. :param worker_ch: :return: """ global keep_running logger.info("Worker subscribing to worker channel...{}_{}".format( actor_id, worker_id)) while keep_running: msg, msg_obj = worker_ch.get_one() # receiving the message is enough to ack it - resiliency is currently handled in the calling code. msg_obj.ack() logger.debug( "Received message in worker channel; msg: {}; {}_{}".format( msg, actor_id, worker_id)) logger.debug("Type(msg)={}".format(type(msg))) if type(msg) == dict: value = msg.get('value', '') if value == 'status': # this is a health check, return 'ok' to the reply_to channel. logger.debug("received health check. returning 'ok'.") ch = msg['reply_to'] ch.put('ok') # @TODO - # delete the anonymous channel from this thread but sleep first to avoid the race condition. time.sleep(1.5) ch.delete() # NOT doing this for now -- deleting entire anon channel instead (see above) # clean up the event queue on this anonymous channel. this should be fixed in channelpy. # ch._queue._event_queue elif msg == 'force_quit': logger.info( "Worker with worker_id: {} (actor_id: {}) received a force_quit message, " "forcing the execution to halt...".format(worker_id, actor_id)) globals.force_quit = True globals.keep_running = False elif msg == 'stop' or msg == 'stop-no-delete': logger.info( "Worker with worker_id: {} (actor_id: {}) received stop message, " "stopping worker...".format(worker_id, actor_id)) globals.keep_running = False # set the worker status to SHUTTING_DOWN: try: Worker.update_worker_status(actor_id, worker_id, SHUTTING_DOWN) except Exception as e: logger.error( f"worker got exception trying to update status to SHUTTING_DOWN. actor_id: {actor_id};" f"worker_id: {worker_id}; exception: {e}") # when an actor's image is updated, old workers are deleted while new workers are # created. Deleting the actor msg channel in this case leads to race conditions delete_actor_ch = True if msg == 'stop-no-delete': logger.info( "Got stop-no-delete; will not delete actor_ch. {}_{}". format(actor_id, worker_id)) delete_actor_ch = False # if a `stop` was sent, the actor is being deleted, and so we want to immediately shutdown processing. else: globals.force_quit = True # first, delete an associated client # its possible this worker was not passed a client, # but if so, we need to delete it before shutting down. if ag_client: logger.info( "worker {}_{} Requesting client {} be deleted.".format( actor_id, worker_id, ag_client.api_key)) secret = os.environ.get('_abaco_secret') clients_ch = ClientsChannel() msg = clients_ch.request_delete_client( tenant=tenant, actor_id=actor_id, worker_id=worker_id, client_id=ag_client.api_key, secret=secret) if msg['status'] == 'ok': logger.info( "Client delete request completed successfully for " "worker_id: {}, client_id: {}.".format( worker_id, ag_client.api_key)) else: logger.error( "Error deleting client for " "worker_id: {}, client_id: {}. Message: {}".format( worker_id, msg['message'], ag_client.api_key)) clients_ch.close() else: logger.info( "Did not receive client. Not issuing delete. Exiting. {}_{}" .format(actor_id, worker_id)) try: Worker.delete_worker(actor_id, worker_id) except WorkerException as e: logger.info("Got WorkerException from delete_worker(). " "worker_id: {}" "Exception: {}".format(worker_id, e)) # delete associated channels: # it is possible the actor channel was already deleted, in which case we just keep processing if delete_actor_ch: try: actor_ch.delete() logger.info( "ActorChannel deleted for actor: {} worker_id: {}". format(actor_id, worker_id)) except Exception as e: logger.info( "Got exception deleting ActorChannel for actor: {} " "worker_id: {}; exception: {}".format( actor_id, worker_id, e)) try: worker_ch.delete() logger.info( "WorkerChannel deleted for actor: {} worker_id: {}".format( actor_id, worker_id)) except Exception as e: logger.info( "Got exception deleting WorkerChannel for actor: {} " "worker_id: {}; exception: {}".format( actor_id, worker_id, e)) logger.info( "Worker with worker_id: {} is now exiting.".format(worker_id)) _thread.interrupt_main() logger.info( "main thread interrupted, worker {}_{} issuing os._exit()...". format(actor_id, worker_id)) os._exit(0)
def timeout(e, timeval=5): time.sleep(timeval) if e.is_set(): return _thread.interrupt_main()
def _handle_timeout(): # Since this is running over a thread, we must propagate the exception # to the main one, and we do this by raising KeyboardInterrupt thread.interrupt_main()
def thread_inference(self): """ Define thread run logic """ while not self.exitflag: if not self.que.empty(): attempt = 1 success_flag = False query_data = self.que.get() query_question = query_data[0] for i in range(self.max_retries): if self.verbose: print("{} processing {}".format( self.name, query_question)) if success_flag: break attempt += 1 try: response = skills_util.retrieve_classifier_response( self.conversation, self.workspace_id, query_question, alternate_intents=True, user_id=self.user_id, ) time.sleep(0.2) if response["intents"]: top_predicts = response["intents"] top_intent = response["intents"][0]["intent"] top_confidence = response["intents"][0][ "confidence"] else: top_predicts = [] top_intent = skills_util.OFFTOPIC_LABEL top_confidence = 0 if response["entities"]: entities = response["entities"] else: entities = [] new_dict = { "utterance": query_question, "correct_intent": query_data[1], "top_intent": top_intent, "top_confidence": top_confidence, "top_predicts": top_predicts, "entities": entities, } self.result.append(new_dict) success_flag = True except Exception: if self.verbose: traceback.print_exc() print("{} process {} fail attempt {}".format( self.name, query_question, i)) time.sleep(0.2) if attempt >= self.max_retries: print("Maximum attempt of {} has reached for query {}". format(self.max_retries, query_question)) _thread.interrupt_main() self.exit() else: self.exit()
def handler(sig): """ Prevents program crashing at CTRL+C event by raising KeyboardInterrupt """ _thread.interrupt_main() return 1
def look_for_control_c(): import msvcrt, _thread while msvcrt.getch() != '\x03': continue _thread.interrupt_main()
def train_1(): import _thread _thread.interrupt_main()
def telegram_bot(rpis, camera): """ This function runs the telegram bot that responds to commands like /enable, /disable or /status. """ def save_chat_id(bot, update): if 'telegram_chat_ids' not in rpis.saved_data or rpis.saved_data[ 'telegram_chat_ids'] is None: rpis.save_telegram_chat_id(update.message.chat_id) logger.debug('Set Telegram chat_id {0}'.format( update.message.chat_id)) else: if len(rpis.saved_data['telegram_chat_ids'] ) < rpis.telegram_users_number: rpis.save_telegram_chat_id(update.message.chat_id) logger.debug('Set Telegram chat_id {0}'.format( update.message.chat_id)) def debug(bot, update): logger.debug('Received Telegram bot message: {0}'.format( update.message.text)) def check_chat_id(update): if 'telegram_chat_ids' in rpis.saved_data and update.message.chat_id not in rpis.saved_data[ 'telegram_chat_ids']: logger.debug( 'Ignoring Telegam update with filtered chat id {0}: {1}'. format(update.message.chat_id, update.message.text)) return False else: return True def help(bot, update): if check_chat_id(update): bot.sendMessage( update.message.chat_id, parse_mode='Markdown', text= '/status: Request status\n/disable: Disable alarm\n/enable: Enable alarm\n/photo: Take a photo\n/gif: Take a gif\n', timeout=10) def status(bot, update): if check_chat_id(update): bot.sendMessage(update.message.chat_id, parse_mode='Markdown', text=rpis.state.generate_status_text(), timeout=10) def disable(bot, update): if check_chat_id(update): rpis.state.update_state('disabled') def enable(bot, update): if check_chat_id(update): rpis.state.update_state('disarmed') def photo(bot, update): if check_chat_id(update): photo = camera.take_photo() rpis.telegram_send_file(photo) def gif(bot, update): if check_chat_id(update): gif = camera.take_gif() rpis.telegram_send_file(gif) def error_callback(bot, update, error): logger.error('Update "{0}" caused error "{1}"'.format(update, error)) try: updater = Updater(rpis.telegram_bot_token) dp = updater.dispatcher dp.add_handler(RegexHandler('.*', save_chat_id), group=1) dp.add_handler(RegexHandler('.*', debug), group=2) dp.add_handler(CommandHandler("help", help), group=3) dp.add_handler(CommandHandler("status", status), group=3) dp.add_handler(CommandHandler("disable", disable), group=3) dp.add_handler(CommandHandler("enable", enable), group=3) dp.add_handler(CommandHandler("photo", photo), group=3) dp.add_handler(CommandHandler("gif", gif), group=3) dp.add_error_handler(error_callback) updater.start_polling(timeout=10) except Exception as e: logger.error('Telegram Updater failed to start with error {0}'.format( repr(e))) _thread.interrupt_main() else: logger.info("thread running")
def call_interrupt(): _thread.interrupt_main()
def quit_function() -> None: display_error("\nPre-receive hook took too long") thread.interrupt_main() # raises KeyboardInterrupt
def test_interrupt_main_mainthread(self): # Make sure that if interrupt_main is called in main thread that # KeyboardInterrupt is raised instantly. with self.assertRaises(KeyboardInterrupt): _thread.interrupt_main()
def background_command_waiter(command, p): p.wait() if p.returncode != 0: warnings.warn( f"Command \"{command}\" exited with status {p.returncode}") _thread.interrupt_main()
def launch(self, bootstrap, pickle): initial = True exceptions = 0 while not self.killed: if not initial: pickle = False bootstrap = False while True: try: self.spawns.update(loadpickle=pickle) except OperationalError as e: self.logger.exception('Operational error while trying to update spawns.') if initial: _thread.interrupt_main() raise OperationalError('Could not update spawns, ensure your DB is setup.') from e time.sleep(20) except Exception: self.logger.exception('A wild exception occurred while updating spawns.') time.sleep(20) else: break if not self.spawns or bootstrap: bootstrap = True pickle = False if bootstrap: self.bootstrap() while len(self.spawns) < 10 and not self.killed: try: mystery_point = list(self.mysteries.popleft()) self.coroutine_semaphore.acquire() asyncio.run_coroutine_threadsafe( self.try_point(mystery_point), loop=self.loop ) except IndexError: if self.spawns.mysteries: self.mysteries = self.spawns.get_mysteries() else: config.MORE_POINTS = True break current_hour = get_current_hour() if self.spawns.after_last(): current_hour += 3600 initial = False if initial: start_point = self.get_start_point() if not start_point: initial = False else: dump_pickle('accounts', self.accounts) for spawn_id, spawn in self.spawns.items(): try: if initial: if spawn_id == start_point: initial = False else: continue try: if self.captcha_queue.qsize() > config.MAX_CAPTCHAS: self.paused = True self.idle_seconds += self.captcha_queue.full_wait(maxsize=config.MAX_CAPTCHAS) self.paused = False except (EOFError, BrokenPipeError, FileNotFoundError): continue point = list(spawn[0]) spawn_time = spawn[1] + current_hour # negative = hasn't happened yet # positive = already happened time_diff = time.time() - spawn_time while time_diff < 0 and not self.killed: try: mystery_point = list(self.mysteries.popleft()) self.coroutine_semaphore.acquire() asyncio.run_coroutine_threadsafe( self.try_point(mystery_point), loop=self.loop ) except IndexError: if self.spawns.mysteries: self.mysteries = self.spawns.get_mysteries() else: config.MORE_POINTS = True break time_diff = time.time() - spawn_time if time_diff > 5 and spawn_id in SIGHTING_CACHE.spawns: self.redundant += 1 continue elif time_diff > config.SKIP_SPAWN: self.skipped += 1 continue if self.killed: return self.coroutine_semaphore.acquire() asyncio.run_coroutine_threadsafe( self.try_point(point, spawn_time), loop=self.loop ) except Exception: exceptions += 1 if exceptions > 100: self.logger.exception('Over 100 errors occured in launcher loop, exiting.') _thread.interrupt_main() else: self.logger.exception('Error occured in launcher loop.')