3 # Copyright (c) 2011 Intel, Inc.
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation; version 2 of the License
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc., 59
16 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 from mic.utils import errors
24 def runtool(cmdln_or_args, catch=1):
25 """ wrapper for most of the subprocess calls
27 cmdln_or_args: can be both args and cmdln str (shell=True)
31 3, both STDOUT and STDERR
34 if catch==0: the output will always None
37 if catch not in (0, 1, 2, 3):
38 # invalid catch selection, will cause exception, that's good
41 if isinstance(cmdln_or_args, list):
42 cmd = cmdln_or_args[0]
46 cmd = shlex.split(cmdln_or_args)[0]
50 sout = subprocess.DEVNULL
51 serr = subprocess.DEVNULL
53 sout = subprocess.PIPE
54 serr = subprocess.DEVNULL
56 sout = subprocess.DEVNULL
57 serr = subprocess.PIPE
59 sout = subprocess.PIPE
60 serr = subprocess.STDOUT
63 p = subprocess.Popen(cmdln_or_args, stdout=sout,
64 stderr=serr, shell=shell, universal_newlines=True)
65 (sout, serr) = p.communicate()
66 # combine stdout and stderr, filter None out
67 out = ''.join([_f for _f in [sout, serr] if _f])
70 # [Errno 2] No such file or directory
71 raise errors.CreatorError('Cannot run command: %s, lost dependency?' % cmd)
77 return (p.returncode, out)
79 def show(cmdln_or_args):
80 # show all the message using msger.verbose
82 rc, out = runtool(cmdln_or_args, catch=3)
84 if isinstance(cmdln_or_args, list):
85 cmd = ' '.join(cmdln_or_args)
89 msg = 'running command: "%s"' % cmd
90 if out: out = out.strip()
92 msg += ', with output::'
93 msg += '\n +----------------'
94 for line in out.splitlines():
95 msg += '\n | %s' % line
96 msg += '\n +----------------'
101 def outs(cmdln_or_args, catch=1):
102 # get the outputs of tools
103 return runtool(cmdln_or_args, catch)[1].strip()
105 def quiet(cmdln_or_args):
106 return runtool(cmdln_or_args, catch=0)[0]