How do I use the subprocess module with mswindows?

Thomas Bellman bellman at lysator.liu.se
Sun Mar 19 06:58:38 EST 2006


Darren Dale <dd55 at cornell.edu> wrote:

> import subprocess
> process = subprocess.Popen(['dir'], stderr=subprocess.STDOUT,
>                 stdout=subprocess.PIPE)
> stat = process.wait()
> print process.stdout.read()

You have already gotten the answer to why 'dir' doesn't work for
you, but there is a bug hiding in that code that you might not
notice in simple tests.

You are waiting for your subprocess to complete without reading
away what it prints.  That will quickly fill the buffer available
in the pipe between you and the subprocess, and the subprocess
will block.  Try calling Popen() with something that prints more
data, like ['find', '/', '-print'] on a Unix box, and you will
notice that problem.

What you should do is:

    output = process.stdout.read()
    stat = process.wait()
    print output

Or, you could use the .communicate() method on the Popen object
instead of .stdout.read().

If you find yourself juggling several subprocesses running in
parallel, producing and/or consuming data "incrementally", or
just trying to handle both sending input to and reading output
from a single subprocess without deadlocking, you may be helped
by using my asyncproc module, which you can download from

    http://www.lysator.liu.se/~bellman/download/asyncproc.py

I suspect that it only works on Unix, though.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Beware of bugs in the above code; I have    !  bellman @ lysator.liu.se
 only proved it correct, not tried it."      !  Make Love -- Nicht Wahr!



More information about the Python-list mailing list