Je t’embrasse Salutations from Silicon Valley, California


commands to subprocess transition

The Python Documentation goes a long way in describing how to transition old code, but for some reason, fails to mention how to transition the legacy "commands.getoutput()" and "commands.getstatusoutput()" functionality into the new Python 2.6+ model of using the subprocess module.

Here is the code required (direct pull/modification of original 2.5 commands module code):

# Get the output from a shell command into a string.
# The exit status is ignored; a trailing newline is stripped.
# Assume the command will work with '{ ... ; } 2>&1' around it..
def getoutput(cmd):
    return getstatusoutput(cmd)[1]

# Ditto but preserving the exit status.
# Returns a pair (sts, output)
def getstatusoutput(cmd):
    import subprocess, os
    p = subprocess.Popen('{ ' + cmd + '; } 2>&1',
                         shell=True, stdout=subprocess.PIPE)
    sts = os.waitpid(, 0)[1]
    text =
    if text[-1:] == '\n': text = text[:-1]
    return sts, text
Filed under: Python No Comments