daksubprocess.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """subprocess management for dak
  2. @copyright: 2013, Ansgar Burchardt <ansgar@debian.org>
  3. @license: GPL-2+
  4. """
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. import signal
  19. import subprocess
  20. #
  21. def fix_signal_handlers():
  22. """reset signal handlers to default action.
  23. Python changes the signal handler to SIG_IGN for a few signals which
  24. causes unexpected behaviour in child processes. This function resets
  25. them to their default action.
  26. Reference: http://bugs.python.org/issue1652
  27. """
  28. for signal_name in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'):
  29. try:
  30. signal_number = getattr(signal, signal_name)
  31. signal.signal(signal_number, signal.SIG_DFL)
  32. except AttributeError:
  33. pass
  34. def _generate_preexec_fn(other_preexec_fn=None):
  35. def preexec_fn():
  36. fix_signal_handlers()
  37. if other_preexec_fn is not None:
  38. other_preexec_fn()
  39. return preexec_fn
  40. def call(*args, **kwargs):
  41. """wrapper around subprocess.call that fixes signal handling"""
  42. preexec_fn = _generate_preexec_fn(kwargs.get('preexec_fn'))
  43. kwargs['preexec_fn'] = preexec_fn
  44. return subprocess.call(*args, **kwargs)
  45. def check_call(*args, **kwargs):
  46. """wrapper around subprocess.check_call that fixes signal handling"""
  47. preexec_fn = _generate_preexec_fn(kwargs.get('preexec_fn'))
  48. kwargs['preexec_fn'] = preexec_fn
  49. return subprocess.check_call(*args, **kwargs)
  50. def check_output(*args, **kwargs):
  51. """wrapper around subprocess.check_output that fixes signal handling"""
  52. preexec_fn = _generate_preexec_fn(kwargs.get('preexec_fn'))
  53. kwargs['preexec_fn'] = preexec_fn
  54. return subprocess.check_output(*args, **kwargs)
  55. def Popen(*args, **kwargs):
  56. """wrapper around subprocess.Popen that fixes signal handling"""
  57. preexec_fn = _generate_preexec_fn(kwargs.get('preexec_fn'))
  58. kwargs['preexec_fn'] = preexec_fn
  59. return subprocess.Popen(*args, **kwargs)