Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transform InterruptHandler to context manager #43

Merged
merged 1 commit into from
Jun 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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