1 """Execute shell commands via os.popen() and return status, output.
7 outtext = commands.getoutput(cmd)
8 (exitstatus, outtext) = commands.getstatusoutput(cmd)
9 outtext = commands.getstatus(file) # returns output of "ls -ld file"
11 A trailing newline is removed from the output string.
13 Encapsulates the basic operation:
15 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
19 [Note: it would be nice to add functions to interpret the exit status.]
22 __all__
= ["getstatusoutput","getoutput","getstatus"]
26 # Various tools for executing commands and looking at their output and status.
28 # NB This only works (and is only relevant) for UNIX.
31 # Get 'ls -l' status for an object into a string
34 """Return output of "ls -ld <file>" in a string."""
35 return getoutput('ls -ld' + mkarg(file))
38 # Get the output from a shell command into a string.
39 # The exit status is ignored; a trailing newline is stripped.
40 # Assume the command will work with '{ ... ; } 2>&1' around it..
43 """Return output (stdout or stderr) of executing cmd in a shell."""
44 return getstatusoutput(cmd
)[1]
47 # Ditto but preserving the exit status.
48 # Returns a pair (sts, output)
50 def getstatusoutput(cmd
):
51 """Return (status, output) of executing cmd in a shell."""
53 pipe
= os
.popen('{ ' + cmd
+ '; } 2>&1', 'r')
56 if sts
is None: sts
= 0
57 if text
[-1:] == '\n': text
= text
[:-1]
61 # Make command argument from directory and pathname (prefix space, add quotes).
65 return mkarg(os
.path
.join(head
, x
))
68 # Make a shell command argument from a string.
69 # Return a string beginning with a space followed by a shell-quoted
70 # version of the argument.
71 # Two strategies: enclose in single quotes if it contains none;
72 # otherwise, enclose in double quotes and prefix quotable characters
77 return ' \'' + x
+ '\''