execute commands and return output

Leif K-Brooks eurleif at ecritters.biz
Sat Sep 10 12:18:29 CEST 2005

billiejoex wrote:
> Hi all. I'm searching for a portable (working on *nix and win32) function 
> that executes a system command and encapsulate its output into a string.
> Searching for the web I found this:
> os.popen('command').read()
> It is perfect but when che command return an error the funciotn returns an 
> empy string.
> Does it is possible to return stdout and stderr too?

Use subprocess:

from subprocess import Popen, PIPE
proc = Popen(['command', 'arg', 'arg'], stdout=PIPE, stderr=PIPE)
return_code = proc.wait()
if return_code == 0:
    print "Success:\n%s" % proc.stdout.read()
    print "Failure %s:\n%s" % (return_code, proc.stderr.read())

More information about the Python-list mailing list