execute.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """execute.py -- Run executable programs.
  2. lvc.execute wraps the standard subprocess module in for LVC.
  3. """
  4. import os
  5. import subprocess
  6. import sys
  7. CalledProcessError = subprocess.CalledProcessError
  8. def default_popen_args():
  9. retval = {
  10. 'stdin': open(os.devnull, 'rb'),
  11. 'stdout': subprocess.PIPE,
  12. 'stderr': subprocess.STDOUT,
  13. }
  14. if sys.platform == 'win32':
  15. retval['startupinfo'] = subprocess.STARTUPINFO()
  16. retval['startupinfo'].dwFlags |= subprocess.STARTF_USESHOWWINDOW
  17. return retval
  18. class Popen(subprocess.Popen):
  19. """subprocess.Popen subclass that adds LVC default behavior.
  20. By default we:
  21. - Use a /dev/null equivilent for stdin
  22. - Use a pipe for stdout
  23. - Redirect stderr to stdout
  24. - use STARTF_USESHOWWINDOW to not open a console window on win32
  25. These are just defaults though, they can be overriden by passing different
  26. values to the constructor
  27. """
  28. def __init__(self, commandline, **kwargs):
  29. final_args = default_popen_args()
  30. final_args.update(kwargs)
  31. subprocess.Popen.__init__(self, commandline, **final_args)
  32. def check_output(commandline, **kwargs):
  33. """LVC version of subprocess.check_output.
  34. This performs the same default behavior as the Popen class.
  35. """
  36. final_args = default_popen_args()
  37. # check_output doesn't use stdout
  38. del final_args['stdout']
  39. final_args.update(kwargs)
  40. return subprocess.check_output(commandline, **final_args)