How do I use the subprocess module with mswindows?

Thomas Bellman bellman at
Sun Mar 19 12:58:38 CET 2006

Darren Dale <dd55 at> wrote:

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

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 =
    stat = process.wait()
    print output

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

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

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 @
 only proved it correct, not tried it."      !  Make Love -- Nicht Wahr!

More information about the Python-list mailing list