(py-outdent-p): new function
[python/dscho.git] / Lib / commands.py
blob6471a8db594c29e1df79dbce42b3b26355be54d9
1 # Module 'commands'
3 # Various tools for executing commands and looking at their output and status.
5 # NB This only works (and is only relevant) for UNIX.
8 # Get 'ls -l' status for an object into a string
10 def getstatus(file):
11 return getoutput('ls -ld' + mkarg(file))
14 # Get the output from a shell command into a string.
15 # The exit status is ignored; a trailing newline is stripped.
16 # Assume the command will work with '{ ... ; } 2>&1' around it..
18 def getoutput(cmd):
19 return getstatusoutput(cmd)[1]
22 # Ditto but preserving the exit status.
23 # Returns a pair (sts, output)
25 def getstatusoutput(cmd):
26 import os
27 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
28 text = pipe.read()
29 sts = pipe.close()
30 if sts == None: sts = 0
31 if text[-1:] == '\n': text = text[:-1]
32 return sts, text
35 # Make command argument from directory and pathname (prefix space, add quotes).
37 def mk2arg(head, x):
38 import os
39 return mkarg(os.path.join(head, x))
42 # Make a shell command argument from a string.
43 # Return a string beginning with a space followed by a shell-quoted
44 # version of the argument.
45 # Two strategies: enclose in single quotes if it contains none;
46 # otherwise, enclose in double quotes and prefix quotable characters
47 # with backslash.
49 def mkarg(x):
50 if '\'' not in x:
51 return ' \'' + x + '\''
52 s = ' "'
53 for c in x:
54 if c in '\\$"`':
55 s = s + '\\'
56 s = s + c
57 s = s + '"'
58 return s