platform.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import signal
  2. try:
  3. from setproctitle import setproctitle as _setproctitle
  4. except ImportError:
  5. _setproctitle = None
  6. def reset_signal(signal_name):
  7. """Reset signal to the default signal handler.
  8. Does nothing if the platform doesn't support signals,
  9. or the specified signal in particular.
  10. """
  11. try:
  12. signum = getattr(signal, signal_name)
  13. signal.signal(signum, signal.SIG_DFL)
  14. except (AttributeError, ValueError):
  15. pass
  16. def ignore_signal(signal_name):
  17. """Ignore signal using :const:`SIG_IGN`.
  18. Does nothing if the platform doesn't support signals,
  19. or the specified signal in particular.
  20. """
  21. try:
  22. signum = getattr(signal, signal_name)
  23. signal.signal(signum, signal.SIG_IGN)
  24. except (AttributeError, ValueError):
  25. pass
  26. def install_signal_handler(signal_name, handler):
  27. """Install a handler.
  28. Does nothing if the current platform doesn't support signals,
  29. or the specified signal in particular.
  30. """
  31. try:
  32. signum = getattr(signal, signal_name)
  33. signal.signal(signum, handler)
  34. except (AttributeError, ValueError):
  35. pass
  36. def set_process_title(progname, info=None):
  37. """Set the ps name for the currently running process.
  38. Only works if :mod`setproctitle` is installed.
  39. """
  40. proctitle = "[%s]" % progname
  41. proctitle = info and "%s %s" % (proctitle, info) or proctitle
  42. if _setproctitle:
  43. _setproctitle(proctitle)
  44. return proctitle
  45. def set_mp_process_title(progname, info=None):
  46. """Set the ps name using the multiprocessing process name.
  47. Only works if :mod:`setproctitle` is installed.
  48. """
  49. from multiprocessing.process import current_process
  50. return set_process_title("%s.%s" % (progname, current_process().name),
  51. info=info)