command.getoutput()

Trent Mick trentm at ActiveState.com
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")
    hi
    >>> retval
    0

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

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

4. When you want to capture stderr too:
    >>> stdin, stdout, stderr = os.popen3("echo hi 1>&2")
    >>> stdin.close()
    >>> output = stdout.read()
    >>> stdout.close()
    >>> error = stderr.read()
    >>> 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
   ActivePython).


Cheers,
Trent

-- 
Trent Mick
TrentM at ActiveState.com





More information about the Python-list mailing list