signal.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import _signal
  2. from _signal import *
  3. from functools import wraps as _wraps
  4. from enum import IntEnum as _IntEnum
  5. _globals = globals()
  6. _IntEnum._convert(
  7. 'Signals', __name__,
  8. lambda name:
  9. name.isupper()
  10. and (name.startswith('SIG') and not name.startswith('SIG_'))
  11. or name.startswith('CTRL_'))
  12. _IntEnum._convert(
  13. 'Handlers', __name__,
  14. lambda name: name in ('SIG_DFL', 'SIG_IGN'))
  15. if 'pthread_sigmask' in _globals:
  16. _IntEnum._convert(
  17. 'Sigmasks', __name__,
  18. lambda name: name in ('SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'))
  19. def _int_to_enum(value, enum_klass):
  20. """Convert a numeric value to an IntEnum member.
  21. If it's not a known member, return the numeric value itself.
  22. """
  23. try:
  24. return enum_klass(value)
  25. except ValueError:
  26. return value
  27. def _enum_to_int(value):
  28. """Convert an IntEnum member to a numeric value.
  29. If it's not an IntEnum member return the value itself.
  30. """
  31. try:
  32. return int(value)
  33. except (ValueError, TypeError):
  34. return value
  35. @_wraps(_signal.signal)
  36. def signal(signalnum, handler):
  37. handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
  38. return _int_to_enum(handler, Handlers)
  39. @_wraps(_signal.getsignal)
  40. def getsignal(signalnum):
  41. handler = _signal.getsignal(signalnum)
  42. return _int_to_enum(handler, Handlers)
  43. if 'pthread_sigmask' in _globals:
  44. @_wraps(_signal.pthread_sigmask)
  45. def pthread_sigmask(how, mask):
  46. sigs_set = _signal.pthread_sigmask(how, mask)
  47. return set(_int_to_enum(x, Signals) for x in sigs_set)
  48. pthread_sigmask.__doc__ = _signal.pthread_sigmask.__doc__
  49. if 'sigpending' in _globals:
  50. @_wraps(_signal.sigpending)
  51. def sigpending():
  52. sigs = _signal.sigpending()
  53. return set(_int_to_enum(x, Signals) for x in sigs)
  54. if 'sigwait' in _globals:
  55. @_wraps(_signal.sigwait)
  56. def sigwait(sigset):
  57. retsig = _signal.sigwait(sigset)
  58. return _int_to_enum(retsig, Signals)
  59. sigwait.__doc__ = _signal.sigwait
  60. del _globals, _wraps