6.23.4. Commands

This module is a replacement for the python commands module, which doesn't work properly on NT.
Start python section to interscript/utilities/commands.py[1 /1 ]
     1: #line 6 "commands.ipk"
     2: """Execute shell commands via os.popen() and return status, output.
     3: 
     4: Interface summary:
     5: 
     6:        import commands
     7: 
     8:        outtext = commands.getoutput(cmd)
     9:        (exitstatus, outtext) = commands.getstatusoutput(cmd)
    10:        outtext = commands.getstatus(file)  # returns output of "ls -ld file"
    11: 
    12: A trailing newline is removed from the output string.
    13: 
    14: Encapsulates the basic operation:
    15: 
    16:       pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
    17:       text = pipe.read()
    18:       sts = pipe.close()
    19: 
    20:  [Note:  it would be nice to add functions to interpret the exit status.]
    21: """
    22: 
    23: # Get the output from a shell command into a string.
    24: # The exit status is ignored; a trailing newline is stripped.
    25: # Assume the command will work with '{ ... ; } 2>&1' around it..
    26: #
    27: def getoutput(cmd):
    28:     """Return output (stdout or stderr) of executing cmd in a shell."""
    29:     return getstatusoutput(cmd)[1]
    30: 
    31: 
    32: # Ditto but preserving the exit status.
    33: # Returns a pair (sts, output)
    34: #
    35: def getstatusoutput(cmd):
    36:     """Return (status, output) of executing cmd in a shell."""
    37:     import os
    38:     import sys
    39:     if sys.platform == 'Win32':
    40:       pipe = os.popen(cmd, 'r')
    41:     else: # assume unix
    42:       pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
    43:     text = pipe.read()
    44:     sts = pipe.close()
    45:     if sts == None: sts = 0
    46:     if text[-1:] == '\n': text = text[:-1]
    47:     return sts, text
    48: 
    49: 
    50: # Make command argument from directory and pathname (prefix space, add quotes).
    51: #
    52: def mk2arg(head, x):
    53:     import os
    54:     return mkarg(os.path.join(head, x))
    55: 
    56: 
    57: # Make a shell command argument from a string.
    58: # Return a string beginning with a space followed by a shell-quoted
    59: # version of the argument.
    60: # Two strategies: enclose in single quotes if it contains none;
    61: # otherwise, enclose in double quotes and prefix quotable characters
    62: # with backslash.
    63: #
    64: def mkarg(x):
    65:     if '\'' not in x:
    66:         return ' \'' + x + '\''
    67:     s = ' "'
    68:     for c in x:
    69:         if c in '\\$"`':
    70:             s = s + '\\'
    71:         s = s + c
    72:     s = s + '"'
    73:     return s
End python section to interscript/utilities/commands.py[1]