Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for getstatusoutput in Python 3

Since the commands module is deprecated since Python 2.6, I'm looking into the best way to replace commands.getstatusoutput which returns a tuple of the command's return code and output. The subprocess module is rather obvious, however, it doesn't offer a direct replacement for getstatusoutput. A potential solution is discussed in a related question concerning getstatusoutput - however, I'm not looking into rewriting the original function (which has less then 10 LOC anyway) but would like to know if there is a more straightforward way.

like image 591
Gerald Senarclens de Grancy Avatar asked Jul 05 '12 12:07

Gerald Senarclens de Grancy


2 Answers

There is no direct replacement, because commands.getstatusoutput was a bad API; it combines stderr and stdout without giving an option to retrieve them separately.

The convenience API that you should be using is subprocess.check_output as it will throw an exception if the command fails.

Otherwise, it does appear somewhat of a deficiency that subprocess doesn't provide a method to retrieve output and status in a single call, but it's easy to work around; here's what the answer to the linked question should have been:

def get_status_output(*args, **kwargs):
    p = subprocess.Popen(*args, **kwargs)
    stdout, stderr = p.communicate()
    return p.returncode, stdout, stderr

If you want stdout and stderr together, use stderr=subprocess.STDOUT.

like image 188
ecatmur Avatar answered Nov 11 '22 06:11

ecatmur


getstatusoutput is back (from python 3.1) :) See: http://docs.python.org/3.3/library/subprocess.html#legacy-shell-invocation-functions

like image 10
Liso Avatar answered Nov 11 '22 06:11

Liso