PyXR

c:\python24\lib \ commands.py



0001 """Execute shell commands via os.popen() and return status, output.
0002 
0003 Interface summary:
0004 
0005        import commands
0006 
0007        outtext = commands.getoutput(cmd)
0008        (exitstatus, outtext) = commands.getstatusoutput(cmd)
0009        outtext = commands.getstatus(file)  # returns output of "ls -ld file"
0010 
0011 A trailing newline is removed from the output string.
0012 
0013 Encapsulates the basic operation:
0014 
0015       pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
0016       text = pipe.read()
0017       sts = pipe.close()
0018 
0019  [Note:  it would be nice to add functions to interpret the exit status.]
0020 """
0021 
0022 __all__ = ["getstatusoutput","getoutput","getstatus"]
0023 
0024 # Module 'commands'
0025 #
0026 # Various tools for executing commands and looking at their output and status.
0027 #
0028 # NB This only works (and is only relevant) for UNIX.
0029 
0030 
0031 # Get 'ls -l' status for an object into a string
0032 #
0033 def getstatus(file):
0034     """Return output of "ls -ld <file>" in a string."""
0035     return getoutput('ls -ld' + mkarg(file))
0036 
0037 
0038 # Get the output from a shell command into a string.
0039 # The exit status is ignored; a trailing newline is stripped.
0040 # Assume the command will work with '{ ... ; } 2>&1' around it..
0041 #
0042 def getoutput(cmd):
0043     """Return output (stdout or stderr) of executing cmd in a shell."""
0044     return getstatusoutput(cmd)[1]
0045 
0046 
0047 # Ditto but preserving the exit status.
0048 # Returns a pair (sts, output)
0049 #
0050 def getstatusoutput(cmd):
0051     """Return (status, output) of executing cmd in a shell."""
0052     import os
0053     pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
0054     text = pipe.read()
0055     sts = pipe.close()
0056     if sts is None: sts = 0
0057     if text[-1:] == '\n': text = text[:-1]
0058     return sts, text
0059 
0060 
0061 # Make command argument from directory and pathname (prefix space, add quotes).
0062 #
0063 def mk2arg(head, x):
0064     import os
0065     return mkarg(os.path.join(head, x))
0066 
0067 
0068 # Make a shell command argument from a string.
0069 # Return a string beginning with a space followed by a shell-quoted
0070 # version of the argument.
0071 # Two strategies: enclose in single quotes if it contains none;
0072 # otherwise, enclose in double quotes and prefix quotable characters
0073 # with backslash.
0074 #
0075 def mkarg(x):
0076     if '\'' not in x:
0077         return ' \'' + x + '\''
0078     s = ' "'
0079     for c in x:
0080         if c in '\\$"`':
0081             s = s + '\\'
0082         s = s + c
0083     s = s + '"'
0084     return s
0085 

Generated by PyXR 0.9.4
SourceForge.net Logo