Trent Mick trentm at
Thu Feb 27 18:06:19 CET 2003

[Peter Wu wrote]
> I'm new to Python. Can you pls show me the code to execute a Win32 command
> in Python? Thanks.

1. Just launching a program where stdout and stderr just get redirected
   to the console:
    >>> retval = os.system("echo hi")
    >>> retval

2. When you want to capture stdout:
    >>> stdout = os.popen("echo hi")
    >>> output =
    >>> retval = stdout.close()
    >>> output
    >>> retval

3. When you want to send something in via stdin:
    >>> stdin, stdout = os.popen2("cat")
    >>> stdin.write("foo\nbar\n")
    >>> stdin.close()
    >>> output =
    >>> retval = stdout.close()
    >>> output
    >>> retval

4. When you want to capture stderr too:
    >>> stdin, stdout, stderr = os.popen3("echo hi 1>&2")
    >>> stdin.close()
    >>> output =
    >>> stdout.close()
    >>> error =
    >>> retval = stderr.close() # the last handle you close returns retval
    >>> output
    >>> error
    'hi \n'
    >>> retval

5. There is also os.popen4 to get stdout and stderr on the same pipe.

6. When you want to start doing fancy things like controlling what pipes
   get passed to the spawned process, controlling whether a console is
   created, controlling process groups, killing processes, etc. then you
   usually have to fallback to using the Win32 APIs for processes (see
   CreateProcess on MSDN). These APIs are mostly available via Mark
   Hammand's PyWin32 extensions (which you already have if you installed


Trent Mick
TrentM at

More information about the Python-list mailing list