command.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright (c) 2011 The Chromium OS Authors.
  2. #
  3. # See file CREDITS for list of people who contributed to this
  4. # project.
  5. #
  6. # This program is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU General Public License as
  8. # published by the Free Software Foundation; either version 2 of
  9. # the License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  19. # MA 02111-1307 USA
  20. #
  21. import os
  22. import subprocess
  23. """Shell command ease-ups for Python."""
  24. def RunPipe(pipeline, infile=None, outfile=None,
  25. capture=False, oneline=False, hide_stderr=False):
  26. """
  27. Perform a command pipeline, with optional input/output filenames.
  28. hide_stderr Don't allow output of stderr (default False)
  29. """
  30. last_pipe = None
  31. while pipeline:
  32. cmd = pipeline.pop(0)
  33. kwargs = {}
  34. if last_pipe is not None:
  35. kwargs['stdin'] = last_pipe.stdout
  36. elif infile:
  37. kwargs['stdin'] = open(infile, 'rb')
  38. if pipeline or capture:
  39. kwargs['stdout'] = subprocess.PIPE
  40. elif outfile:
  41. kwargs['stdout'] = open(outfile, 'wb')
  42. if hide_stderr:
  43. kwargs['stderr'] = open('/dev/null', 'wb')
  44. last_pipe = subprocess.Popen(cmd, **kwargs)
  45. if capture:
  46. ret = last_pipe.communicate()[0]
  47. if not ret:
  48. return None
  49. elif oneline:
  50. return ret.rstrip('\r\n')
  51. else:
  52. return ret
  53. else:
  54. return os.waitpid(last_pipe.pid, 0)[1] == 0
  55. def Output(*cmd):
  56. return RunPipe([cmd], capture=True)
  57. def OutputOneLine(*cmd):
  58. return RunPipe([cmd], capture=True, oneline=True)
  59. def Run(*cmd, **kwargs):
  60. return RunPipe([cmd], **kwargs)
  61. def RunList(cmd):
  62. return RunPipe([cmd], capture=True)