Reduce ThreadManager default worker_thread to 2.
[sawsim.git] / pysawsim / invoke.py
1 # Copyright (C) 2009-2010  W. Trevor King <wking@drexel.edu>
2 #
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
15 #
16 # The author may be contacted at <wking@drexel.edu> on the Internet, or
17 # write to Trevor King, Drexel University, Physics Dept., 3141 Chestnut St.,
18 # Philadelphia PA 19104, USA.
19
20 """Functions for running external commands in subprocesses.
21 """
22
23 from subprocess import Popen, PIPE
24 import sys
25
26
27 class CommandError(Exception):
28     def __init__(self, command, status, stdout, stderr):
29         strerror = ["Command failed (%d):\n  %s\n" % (status, stderr),
30                     "while executing\n  %s" % command]
31         Exception.__init__(self, "\n".join(strerror))
32         self.command = command
33         self.status = status
34         self.stdout = stdout
35         self.stderr = stderr
36
37 def invoke(cmd_string, stdin=None, expect=(0,), cwd=None, verbose=False):
38     """
39     expect should be a tuple of allowed exit codes.  cwd should be
40     the directory from which the command will be executed.
41     """
42     if cwd == None:
43         cwd = "."
44     if verbose == True:
45         print >> sys.stderr, "%s$ %s" % (cwd, cmd_string)
46     try :
47         if sys.platform != "win32" and False:
48             q = Popen(cmd_string, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=cwd)
49         else:
50             # win32 don't have os.execvp() so have to run command in a shell
51             q = Popen(cmd_string, stdin=PIPE, stdout=PIPE, stderr=PIPE,
52                       shell=True, cwd=cwd)
53     except OSError, e :
54         raise CommandError(cmd_string, status=e.args[0], stdout="", stderr=e)
55     stdout,stderr = q.communicate(input=stdin)
56     status = q.wait()
57     if verbose == True:
58         print >> sys.stderr, "%d\n%s%s" % (status, stdout, stderr)
59     if status not in expect:
60         raise CommandError(cmd_string, status, stdout, stderr)
61     return status, stdout, stderr