def menu(self, command=None): if command: self.state = self.view.num_command(command) else: self.state = self.view.menu_selector() if self.state == 'exit': signal.raise_signal(signal.SIGINT) try: self.model.state = self.state if hasattr(self, self.state): getattr(self, self.state)() elif self.state not in { None, 'initialize', 'exit', 'account_info' }: LOGGER.warning('cannot find attr for state: %s', self.state) except HTTPError as err: LOGGER.error(err) errmsg = str(err) if errmsg.startswith('400 Client Error: Bad Request for url: '): self.view.vio.print('Operation failed. ' + GENERIC_CAUTION) else: self.view.vio.print( 'HTTP error occurred. Check the network conditions.') except ValueError as err: # short of Ether, permission denied, or reverted. maybe... LOGGER.error(err) self.view.vio.print('Operation failed. ' + GENERIC_CAUTION)
def blit_gameover(self) -> None: os.system("clear") message = f""" {" " * ((self.width // 2) - 10)} GAME OVER! {" " * ((self.width // 2) - 10)}⣿⣿⣿⠟⠛⠛⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⢋⣩⣉⢻⣿ {" " * ((self.width // 2) - 10)}⣿⣿⣿⠀⣿⣶⣕⣈⠹⠿⠿⠿⠿⠟⠛⣛⢋⣰⠣⣿⣿⠀⣿ {" " * ((self.width // 2) - 10)}⣿⣿⣿⡀⣿⣿⣿⣧⢻⣿⣶⣷⣿⣿⣿⣿⣿⣿⠿⠶⡝⠀⣿ {" " * ((self.width // 2) - 10)}⣿⣿⣿⣷⠘⣿⣿⣿⢏⣿⣿⣋⣀⣈⣻⣿⣿⣷⣤⣤⣿⡐⢿ {" " * ((self.width // 2) - 10)}⣿⣿⣿⣿⣆⢩⣝⣫⣾⣿⣿⣿⣿⣿⣿⣿⠦⠀⠸⣿⣿⡄⢻ {" " * ((self.width // 2) - 10)}⣿⣿⣿⣿⣿⡄⢻⣿⣿⣿⣿⣿⣿⡟⠀⠀⠀⠀⠀⠀⢻⠇⣼ {" " * ((self.width // 2) - 10)}⣿⣿⣿⣿⣿⣿⡄⢿⣿⣿⣿⣿⣿⠀⠀noob⠀ ⡟⣰ {" " * ((self.width // 2) - 10)}⣿⣿⣿⣿⣿⣿⠇⣼⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⣼⢀⣿ {" " * ((self.width // 2) - 10)}⣿⣿⣿⣿⣿⠏⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸⣿ {" " * ((self.width // 2) - 10)}⣿⣿⣿⣿⠟⣰⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣿ {" " * ((self.width // 2) - 10)}⣿⣿⣿⠋⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄⣿ {" " * ((self.width // 2) - 10)}⣿⣿⠋⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢸ {" " * ((self.width // 2) - 10)}⣿⠏⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢸ {" " * ((self.width // 2) - 10)} SCORE: {self.score} {" " * ((self.width // 2) - 10)} Press Esc to quit. """ sys.stdout.write("\n" * (self.height // 4)) sys.stdout.write(" " * ((self.width // 2) - (len(message) // 2))) sys.stdout.write(message) sys.stdout.flush() sys.stdout.write(self.cursor["RESET"]()) # exit game if self.pressed == "\x1b": signal.raise_signal(2)
def exception_handler(loop, context): # TODO figure our exception handling and interrupts for all the processes # TODO https://quantlane.com/blog/ensure-asyncio-task-exceptions-get-logged/ # TODO make an untility funcrion and move to utils? # first, handle with default handler loop.default_exception_handler(context) signal.raise_signal(signal.SIGTERM)
def blit_completed(self) -> None: os.system("clear") message = f""" {" " * ((self.width // 2) - 8)} YOU WIN! {" " * ((self.width // 2) - 8)} ⢀⣀⣀⣄⣶⡶⣦⣀ {" " * ((self.width // 2) - 8)} ⢠⡦⡟⠻⠛⠙⠉⠈⠄⠄⠈⠻⠛⣾⣦⣤⣀ {" " * ((self.width // 2) - 8)} ⣰⡿⠟⠃⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠘⠋⠽⢿⣧ {" " * ((self.width // 2) - 8)}⢀⣴⠞⠂⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⢼⠆ {" " * ((self.width // 2) - 8)}⣼⠇⠄⠄⠄⠄⠄⠄⠄⠄⣀⣠⣤⣶⣿⣶⣦⣤⣀⠄⣻⡃ {" " * ((self.width // 2) - 8)}⡿⠄⠄⠄⠄⠄⠄⠄⠄⠄⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⢸⣧ {" " * ((self.width // 2) - 8)}⢿⡀⠄⠄⠄⠄⠄⠄⠄⢠⣾⣿⣿⣋⣩⣭⣝⣿⣿⠛⢰⡇ {" " * ((self.width // 2) - 8)}⢸⡇⠄⠄⢀⠄⠄⠄⠄⣾⣿⣿⣿⣟⣯⠉⢉⣿⠋⣟⢻⡇ {" " * ((self.width // 2) - 8)} ⢹⡀⢳⡗⠂⣠⠄⠄⣿⣿⣿⣿⣿⣭⣽⣿⣿⣿⣉⣸⠇ {" " * ((self.width // 2) - 8)} ⠈⣷⠄⢳⣷⣿⠄⠄⢹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇ {" " * ((self.width // 2) - 8)} ⠘⣧⠄⠈⠙⠄⠄⠄⠉⠙⠛⠛⣿⣿⣷⣤⣄⢿⡿⠃ {" " * ((self.width // 2) - 8)} ⠉⠳⣄⡀⠄⠄⠄⢢⣦⣾⣿⠿⠿⠛⠉⢉⣽⠇ {" " * ((self.width // 2) - 8)} ⠘⠿⣄⢀⠄⣀⣝⢻⣿⡿⠒⣀⣀⣸⠁ {" " * ((self.width // 2) - 8)} ⠈⠳⣤⠁⠙⠎⢻⣄⠄⠄⣸⠋ {" " * ((self.width // 2) - 8)} ⠈⠙⠶⢦⣄⣀⣣⠴⠃ {" " * ((self.width // 2) - 8)} SCORE: {self.score} {" " * ((self.width // 2) - 8)} Press Esc to quit. """ sys.stdout.write("\n" * (self.height // 4)) sys.stdout.write(" " * ((self.width // 2) - (len(message) // 2))) sys.stdout.write(message) sys.stdout.flush() sys.stdout.write(self.cursor["RESET"]()) # exit game if self.pressed == "\x1b": signal.raise_signal(2)
def handler(signum, frame): logger.info("Signal handler called with signal SIGTERM") logger.info("Shutdown crawler") crawler.cancel() crawler.join() signal.signal(signal.SIGTERM, signal.SIG_DFL) signal.raise_signal(signum)
def connection_lost(self, exc): sys.stdout.write( f"Lost connection to {self.transport.get_extra_info('peername')}\r\n" ) sys.stdout.flush() self.transport = None signal.raise_signal(signal.SIGTERM)
def yakala(mq): mesaj, _ = mq.receive() if (mesaj == "BYE"): print("Kuyruk kapandı") signal.raise_signal(signal.SIGINT) print("Renk: " + mesaj.decode("ascii")) mq.request_notification((yakala, mq))
async def _signal_test(sigs, mypid): sigstream = streams.ReadableStream(sigs) count = 0 while count < 5: signal.raise_signal(signal.SIGUSR1) siginfo = await sigstream.read() assert siginfo.signo == signal.SIGUSR1 count += 1
def move(self, game) -> None: if not game.playing: try: paddle = list(filter(lambda e: type(e).__name__ == "Paddle", game.entities))[0] self.position = np.array( [paddle.position[0] + paddle.dimens[0] // 2, self.start_position[1]] ) except: pass try: collision = self.collides(game.board) if collision: # make collision sound if SOUND_ENABLED: print("\a") # if collided with a brick, hit it if type(collision).__name__ == "Brick": collision.hit(game) if type(collision).__name__ == "Paddle": delta = collision.dimens[0] / 5 if 0 <= self.position[0] - collision.position[0] < delta: self.velocity = np.array([-3, -1]) elif (delta) <= self.position[0] - collision.position[0] < (2 * delta): self.velocity = np.array([-2, -1]) elif (3 * delta) <= self.position[0] - collision.position[0] < (4 * delta): self.velocity = np.array([2, -1]) elif (4 * delta) <= self.position[0] - collision.position[0] < (5 * delta): self.velocity = np.array([3, -1]) else: self.velocity *= np.array([1, -1]) # make bricks fall after each hit after crossing threshold current_time = int(round(time.time() - game.start_time, 0)) if current_time > FALLING_THRESHOLD: for entity in game.entities: if type(entity).__name__ == "Brick": entity.position += np.array([0, 1]) # implement game over when bricks hit paddle if entity.position[1] > game.height - 3: game.remaining_lives = 1 signal.raise_signal(10) else: available = self.available(game.board) W, E, N, S = [int(available[k]) for k in ("W", "E", "N", "S")] if not W or not E: self.velocity *= np.array([-1, 1]) if not N or not S: self.velocity *= np.array([1, -1]) self.position += self.velocity except: # implement game over when ball goes below border signal.raise_signal(10)
def raise_signal(signal_num: int, pid: int = None) -> None: num_times = 3 if os.name == 'nt' else 1 if not pid and py38: for i in range(0, num_times): signal.raise_signal(signal_num) else: pid = pid or os.getpid() for i in range(0, num_times): os.kill(pid, signal_num)
def test_handler(self): is_ok = False def handler(a, b): nonlocal is_ok is_ok = True old_signal = signal.signal(signal.SIGINT, handler) self.addCleanup(signal.signal, signal.SIGINT, old_signal) signal.raise_signal(signal.SIGINT) self.assertTrue(is_ok)
def test_invalid_argument(self): try: SIGHUP = 1 # not supported on win32 signal.raise_signal(SIGHUP) self.fail("OSError (Invalid argument) expected") except OSError as e: if e.errno == errno.EINVAL: pass else: raise
def test_handler(self): is_ok = False def handler(a, b): nonlocal is_ok is_ok = True old_signal = signal.signal(signal.SIGINT, handler) self.addCleanup(signal.signal, signal.SIGINT, old_signal) signal.raise_signal(signal.SIGINT) self.assertTrue(is_ok)
def handle_stdin(self): line = sys.stdin.readline() if self.transport is not None: if line == "": # Got a ^D self.transport.close() signal.raise_signal(signal.SIGTERM) else: line = line.strip() self.transport.write(line + "\r") else: sys.stdout.write("Not connected\n") sys.stdout.flush()
def handle_stdin(self): line = sys.stdin.readline() if self.context is not None: if line == "": # Got a ^D self.context.close() signal.raise_signal(signal.SIGTERM) else: line = line.strip() self.context.write("ff.ff", f"{line}\r\n".encode("utf-8")) else: sys.stdout.write("Not connected\r\n") sys.stdout.flush()
def interrupt_if_cancelling() -> None: # We need to copy the context into this thread, since context is a # thread local. with prefect.context(context): flow_run_id = prefect.context["flow_run_id"] while True: exiting_context = done.wait( prefect.config.cloud.check_cancellation_interval) try: self.logger.debug("Checking flow run state...") flow_run_info = self.client.get_flow_run_info( flow_run_id) except Exception: self.logger.warning("Error getting flow run info", exc_info=True) continue if not flow_run_info.state.is_running(): self.logger.warning( "Flow run is no longer in a running state; the current state is: %r", flow_run_info.state, ) if isinstance(flow_run_info.state, Cancelling): self.logger.info( "Flow run has been cancelled, cancelling active tasks" ) nonlocal cancelling nonlocal flow_run_version cancelling = True flow_run_version = flow_run_info.version # If not already leaving context, raise KeyboardInterrupt in the main thread if not exiting_context: if hasattr(signal, "raise_signal"): # New in python 3.8 signal.raise_signal( signal.SIGINT) # type: ignore else: if os.name == "nt": # This doesn't actually send a signal, so it will only # interrupt the next Python bytecode instruction - if the # main thread is blocked in a c extension the interrupt # won't be seen until that returns. from _thread import interrupt_main interrupt_main() else: signal.pthread_kill( threading.main_thread().ident, signal.SIGINT # type: ignore ) break elif exiting_context: break
def test_signal_handler(): handler = SignalsEventHandler() is_caught = False # caught def do_on_signal(signal: Signals, frame: FrameType): nonlocal is_caught is_caught = True handler.on(Signals.SIGTERM, do_on_signal) raise_signal(Signals.SIGTERM.value) handler.clear(Signals.SIGTERM) assert is_caught, "Signal not caught"
def sigint_handler(sig, frame): """Thread safe SIGINT interrupting""" set_end() if sys.platform != "win32": signal.signal(signal.SIGINT, prev_sigint_handler) threading.Thread(target=signal.raise_signal(signal.SIGINT)).start()
def interrupt_local_process() -> None: """Meant to be executed from a background thread""" import signal if hasattr(signal, "raise_signal"): # Python 3.8 and later signal.raise_signal(signal.SIGINT) elif sys.platform == "win32": # https://stackoverflow.com/a/51122690/261181 import ctypes ucrtbase = ctypes.CDLL("ucrtbase") c_raise = ucrtbase["raise"] c_raise(signal.SIGINT) else: # Does not give KeyboardInterrupt in Windows os.kill(os.getpid(), signal.SIGINT)
def sigint_handler(sig, frame): set_end() if sys.platform != 'win32': signal.signal(signal.SIGINT, prev_sigint_handler) threading.Thread(target=signal.raise_signal(signal.SIGINT)).start() else: kill_processes('python.exe') kill_processes('PTS.exe') kill_processes('Fts.exe')
def estop(self): signal.signal(signal.SIGILL, self.handler1) data = display.Display().screen().root.query_pointer()._data p = path.Path([(120, 805), (234, 805), (306, 878), (306, 991), (234, 1064), (121, 1064), (48, 991), (48, 878)]) # Define Octogon contains = p.contains_points([(data["root_x"], data["root_y"])]) # Check if cursor is inside the stop sign if contains: # Cursor enters box if not self.timer_running: self.timer_start = rospy.get_time() self.timer_running = True # Cursor remains in box if self.timer_running: self.timer = rospy.get_time() - self.timer_start else: # Cursor leaves box if self.timer_running: self.timer_running = False self.timer_start = 0 self.timer = 0 if self.timer > self.estop_dwell_time + self.estop_delay_time: # print("Object Selected!") self.timer_running = False self.timer_start = 0 self.timer = 0 raf_msg = "E-stop Pressed." self.change_raf_message(raf_msg) self.publish() print("E-stop Pressed. Exiting Program.") signal.raise_signal(signal.SIGINT) self.cursor_angle = self.linear_map( self.estop_delay_time, self.estop_dwell_time, 0, 2 * math.pi, np.clip(self.timer, self.estop_delay_time, self.estop_dwell_time))
def __exit__(self, type, value, traceback): # restore the original handler whatever it was original, self.original = self.original, None if original is not None: signal(SIGINT, original) # do not keep reference to the interrupted stack frame captured, self.captured = self.captured, None # If no exception was supplied, but we captured a KeyboardInterrupt, # then we are 'delay', since `captured` is always `None` otherwise. if type is None and captured is not None: # re-raise the interrupt or call the original handler if callable(original): original(*captured) else: raise_signal(SIGINT) # prioritize bubbling up all other exceptions pass
def test_delay(self): saw_sigterm = False def capture_sigterm(*args, **kwargs): nonlocal saw_sigterm saw_sigterm = True og_sigterm_handler = signal.signal(signal.SIGTERM, capture_sigterm) try: with signal_helper.delay_signals(): self.assertFalse(saw_sigterm) if hasattr(signal, 'raise_signal'): # 3.8+ signal.raise_signal(signal.SIGTERM) else: os.kill(os.getpid(), signal.SIGTERM) self.assertFalse(saw_sigterm) self.assertTrue(saw_sigterm) finally: signal.signal(signal.SIGTERM, og_sigterm_handler)
def test_sigint(self): with self.assertRaises(KeyboardInterrupt): signal.raise_signal(signal.SIGINT)
async def raise_signal() -> None: await ready_event.wait() signal.raise_signal(signal.SIGWINCH)
def SIGINT_after_delay(): time.sleep(0.1) signal.raise_signal(signal.SIGINT)
def blit(self) -> None: current_time = int(round(time.time() - self.start_time, 0)) # update game state level_incomplete = 0 self.reset() for entity in self.entities: # check for level clearance if type(entity).__name__ == "Brick" and entity.health > 0: level_incomplete += 1 if entity.id == "boss": level_incomplete = 1 # update powerup status if hasattr(entity, "active_powerup"): if (entity.active_powerup.expires <= time.time()) or not level_incomplete: entity.active_powerup.deactivate(entity) y, x = entity.position entity.move(self) for h in range(entity.dimens[1]): for w in range(entity.dimens[0]): self.board[x + h][y + w] = entity # render current game state for i in range(self.height): for j in range(self.width): sys.stdout.write(self.cursor["RESET"]()) sys.stdout.write(f"{self.cursor['DOWN'](i - 1)}{self.cursor['RIGHT'](j - 1)}") if i == 2 and (1 < j < self.width - 1): # display time & lives if j == 3: sys.stdout.write(f"TIME: {current_time:05} LIVES: {self.remaining_lives}") # display level & score if j == self.width - (20 + len(str(self.score))): sys.stdout.write(f"LEVEL: {self.level} SCORE: {self.score}") # display entities elif self.board[i][j]: sys.stdout.write( f"{self.board[i][j].color}{self.board[i][j].sprite}{Fore.RESET}" ) else: sys.stdout.write(" ") if not self.playing and not self.game_over: sys.stdout.write(self.cursor["RESET"]()) sys.stdout.write( f"{self.cursor['DOWN'](self.height // 2)}{self.cursor['RIGHT']((self.width // 2) - 8)}" ) sys.stdout.write("Press W to start.") sys.stdout.flush() sys.stdout.write(self.cursor["RESET"]()) if not level_incomplete: self.next_level() return # start level if self.pressed == "w": signal.raise_signal(12) # skip level backdoor if self.pressed == "l": signal.raise_signal(5)
def _sig_dfl(sig, stack): """A signal handler behaving like signal.SIG_DFL""" # Restore the DLF handler signal.signal(sig, signal.SIG_DFL) # Raise either SIGHUP or SIGTERM, which terminates the process signal.raise_signal(sig)
def sig_handler(signal_name, frame, event, url_counter, sock): event.set() sock.close() print(f'total urls parsed: {url_counter.num}') signal.raise_signal(signal.SIGKILL) sys.exit(1)
def test_sigint(self): try: signal.raise_signal(signal.SIGINT) self.fail("Expected KeyInterrupt") except KeyboardInterrupt: pass
def set_interrupts(): nonlocal num_sent_signals while not do_stop: signal.raise_signal(signum) num_sent_signals += 1
def wait_for_pager_signal(signo, frame): close_pager_fds() pager.wait() for signo, handler in handlers.items(): signal.signal(signo, handler) signal.raise_signal(signo)