Skip to content

Commit

Permalink
Transform InterruptHandler to context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
cyc60 committed Jun 28, 2023
1 parent 4491a57 commit 4c97b32
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions sw_utils/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,30 @@
class InterruptHandler:
"""
Tracks SIGINT and SIGTERM signals.
Usage:
with InterruptHandler() as interrupt_handler:
while not interrupt_handler.exit:
...
"""

exit = False

def __init__(self) -> None:
def __enter__(self) -> 'InterruptHandler':
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
return self

def __exit__(self, exc_type, exc_val, exc_tb):
signal.signal(signal.SIGINT, self.exit_default)
signal.signal(signal.SIGTERM, self.exit_default)

# noinspection PyUnusedLocal
def exit_gracefully(self, signum: int, *args, **kwargs) -> None:
# pylint: disable=unused-argument
if self.exit:
raise KeyboardInterrupt
logger.info('Received interrupt signal %s, exiting...', signum)
self.exit = True

def exit_default(self, signum: int, *args, **kwargs) -> None:
# pylint: disable=unused-argument
raise KeyboardInterrupt

0 comments on commit 4c97b32

Please sign in to comment.