exit_on_sig_term.py 834 B

1234567891011121314151617181920212223242526
  1. # Copyright 2022 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. import signal
  5. import sys
  6. # TODO(grt): Derive from contextlib.AbstractContextManager when p3 is supported.
  7. class ExitOnSigTerm():
  8. """A context manager that calls sys.exit(0) upon receipt of SIGTERM. This
  9. results in a SystemExit exception being raised, which causes any finally
  10. clauses to be run and other contexts to be cleaned up.
  11. """
  12. def __init__(self):
  13. self._previous_handler = None
  14. def __enter__(self):
  15. self._previous_handler = signal.signal(
  16. signal.SIGTERM, lambda sig_num, frame: sys.exit(0))
  17. return self
  18. def __exit__(self, exc_type, exc_val, exc_tb):
  19. signal.signal(signal.SIGTERM, self._previous_handler)
  20. return False