bash command, get stdErr

Chris Rebert clp2 at rebertia.com
Thu Aug 25 04:52:25 EDT 2011


On Thu, Aug 25, 2011 at 1:25 AM, Tracubik <affdfsdfdsfsd at b.com> wrote:
> Hi all!
> i'ld like to execute via Python this simple bash command:
>
> sudo las
>
> las is intended to be a typo for "ls"
>
> the point is that i want to see in the terminal the stderr message (that
> is "sorry, try again" if i insert the wrong password or "sudo: las:
> command not found" otherwise)
>
> i can simply do it with subprocess.POpen() or subprocess.Call() but as
> far as i know i have two choice:
> 1) s = subprocess.Popen('sudo las', shell=True, stderr=subprocess.PIPE)
>
> in this way i catch the stderr messages BUT they are not "printed" in the
> terminal
>
> 2) s = subprocess.Popen('sudo las', shell=True, stderr=none)
> in this way i "print" the message in the terminal but i can retrieve they
> (the error messages) when the command is executed
<snip>
> Still, it's not good to don't give
> feedback of the error to the user, so i'ld like to print the stderr on
> terminal AND get it after the command terminate to check the problem
> occurred (exit status is not enough).

Untested:

from subprocess import Popen, PIPE
sudo = Popen("sudo las", shell=True, stderr=PIPE)
tee = Popen(["tee", "/dev/stderr"], stdin=sudo.stderr, stdout=PIPE)
# Read from tee.stdout to get any error messages

Further info: http://en.wikipedia.org/wiki/Tee_%28command%29

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list