Quick update to the README file. For intros and books we now point to
[python/dscho.git] / Lib / commands.py
blob12acc364087e0f3f35f991f4678c408e713cbcab
1 """Execute shell commands via os.popen() and return status, output.
3 Interface summary:
5 import commands
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')
16 text = pipe.read()
17 sts = pipe.close()
19 [Note: it would be nice to add functions to interpret the exit status.]
20 """
22 # Module 'commands'
24 # Various tools for executing commands and looking at their output and status.
26 # NB This only works (and is only relevant) for UNIX.
29 # Get 'ls -l' status for an object into a string
31 def getstatus(file):
32 """Return output of "ls -ld <file>" in a string."""
33 return getoutput('ls -ld' + mkarg(file))
36 # Get the output from a shell command into a string.
37 # The exit status is ignored; a trailing newline is stripped.
38 # Assume the command will work with '{ ... ; } 2>&1' around it..
40 def getoutput(cmd):
41 """Return output (stdout or stderr) of executing cmd in a shell."""
42 return getstatusoutput(cmd)[1]
45 # Ditto but preserving the exit status.
46 # Returns a pair (sts, output)
48 def getstatusoutput(cmd):
49 """Return (status, output) of executing cmd in a shell."""
50 import os
51 pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
52 text = pipe.read()
53 sts = pipe.close()
54 if sts == None: sts = 0
55 if text[-1:] == '\n': text = text[:-1]
56 return sts, text
59 # Make command argument from directory and pathname (prefix space, add quotes).
61 def mk2arg(head, x):
62 import os
63 return mkarg(os.path.join(head, x))
66 # Make a shell command argument from a string.
67 # Return a string beginning with a space followed by a shell-quoted
68 # version of the argument.
69 # Two strategies: enclose in single quotes if it contains none;
70 # otherwise, enclose in double quotes and prefix quotable characters
71 # with backslash.
73 def mkarg(x):
74 if '\'' not in x:
75 return ' \'' + x + '\''
76 s = ' "'
77 for c in x:
78 if c in '\\$"`':
79 s = s + '\\'
80 s = s + c
81 s = s + '"'
82 return s