0
|
1 # Copyright (C) 2007 by Intevation GmbH |
|
2 # Authors: |
|
3 # Bernhard Herzog <bh@intevation.de> |
|
4 # |
|
5 # This program is free software under the GPL (>=v2) |
|
6 # Read the file COPYING coming with the software for details. |
|
7 |
|
8 """Helper functions to run subprocesses in various ways""" |
|
9 |
|
10 import os |
|
11 import subprocess |
|
12 |
|
13 |
|
14 class SubprocessError(EnvironmentError): |
|
15 |
|
16 def __init__(self, command, returncode): |
|
17 EnvironmentError.__init__(self, |
|
18 "Command %r finished with return code %d" |
|
19 % (command, returncode)) |
|
20 self.returncode = returncode |
|
21 |
|
22 |
|
23 def call(command, suppress_output=False, **kw): |
|
24 """Run command as a subprocess and wait until it is finished. |
|
25 |
|
26 The command should be given as a list of strings to avoid problems |
|
27 with shell quoting. If the command exits with a return code other |
|
28 than 0, a SubprocessError is raised. |
|
29 """ |
|
30 if suppress_output: |
|
31 kw["stdout"] = open(os.devnull, "w") |
|
32 ret = subprocess.call(command, **kw) |
|
33 if ret != 0: |
|
34 raise SubprocessError(command, ret) |
|
35 |
|
36 |
|
37 def capture_output(command, **kw): |
|
38 """Return the stdout and stderr of the command as a string |
|
39 |
|
40 The command should be given as a list of strings to avoid problems |
|
41 with shell quoting. If the command exits with a return code other |
|
42 than 0, a SubprocessError is raised. |
|
43 """ |
|
44 proc = subprocess.Popen(command, stdout=subprocess.PIPE, |
|
45 stderr=subprocess.STDOUT, **kw) |
|
46 output = proc.communicate()[0] |
|
47 if proc.returncode != 0: |
|
48 raise SubprocessError(command, proc.returncode) |
|
49 return output |