Debian Codegraph @

py/_process/cmdexec.py

raw symbols SCIP
1 import sys
2 import subprocess
3 import py
4 from subprocess import Popen, PIPE
5
6 def cmdexec(cmd):
7 """ return unicode output of executing 'cmd' in a separate process.
8
9 raise cmdexec.Error exeception if the command failed.
10 the exception will provide an 'err' attribute containing
11 the error-output from the command.
12 if the subprocess module does not provide a proper encoding/unicode strings
13 sys.getdefaultencoding() will be used, if that does not exist, 'UTF-8'.
14 """
15 process = subprocess.Popen(cmd, shell=True,
16 universal_newlines=True,
17 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
18 out, err = process.communicate()
19 if sys.version_info[0] < 3: # on py3 we get unicode strings, on py2 not
20 try:
21 default_encoding = sys.getdefaultencoding() # jython may not have it
22 except AttributeError:
23 default_encoding = sys.stdout.encoding or 'UTF-8'
24 out = unicode(out, process.stdout.encoding or default_encoding)
25 err = unicode(err, process.stderr.encoding or default_encoding)
26 status = process.poll()
27 if status:
28 raise ExecutionFailed(status, status, cmd, out, err)
29 return out
30
31 class ExecutionFailed(py.error.Error):
32 def __init__(self, status, systemstatus, cmd, out, err):
33 Exception.__init__(self)
34 self.status = status
35 self.systemstatus = systemstatus
36 self.cmd = cmd
37 self.err = err
38 self.out = out
39
40 def __str__(self):
41 return "ExecutionFailed: %d %s\n%s" %(self.status, self.cmd, self.err)
42
43 # export the exception under the name 'py.process.cmdexec.Error'
44 cmdexec.Error = ExecutionFailed
45 try:
46 ExecutionFailed.__module__ = 'py.process.cmdexec'
47 ExecutionFailed.__name__ = 'Error'
48 except (AttributeError, TypeError):
49 pass