Correctly reading stdout/stderr from subprocess
Christoph Haas
email at christoph-haas.de
Wed Jun 14 13:56:17 EDT 2006
On Wed, Jun 14, 2006 at 03:56:16PM +0200, Maric Michaud wrote:
> I did it just to validate my point and because i don't use threads very often
> in python, some exercises can't hurt :)
Since you are familiar with threads I believe that my excercises are a
tad bit more low-level compared to yours. :)
> def run(command):
>
> import subprocess
>
> run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,
> stderr=subprocess.PIPE)
>
> # Wait for the process to return
> import thread, threading
> out, err = [], []
> out_ended, err_ended = threading.Event(), threading.Event()
>
> def getOutput(output, lines, ended_event) :
> for i in output.readlines() : lines.append(i.rstrip('\n'))
> ended_event.set()
>
> out_thread = thread.start_new_thread(getOutput, (run.stdout, out,
> out_ended))
> err_thread = thread.start_new_thread(getOutput, (run.stderr, err,
> err_ended))
>
> out_ended.wait()
> err_ended.wait()
>
> returncode = run.wait()
>
> return returncode, out, err
Quite interesting. I dived into /usr/lib/python2.4/subprocess.py and
found out that the "communicate()" method actually works similarly. I
might even prefer your version because I get the returncode from
run.wait() what "communicate()" does not.
Great work. Thanks for your time.
Kindly
Christoph
More information about the Python-list
mailing list