[Tutor] os.system call

Michael P. Reilly arcege@shore.net
Fri, 17 Nov 2000 10:09:53 -0500 (EST)

> Hey All,
>    Is there a way to run an os.system type call and capture the ouput in python.  The only way I have found is to redirect the output of the system call to a file, then open the file and read in the results.  Any help is appreciated.
> Thanks,
> Matthew

You can either use os.popen() to get just the output.  Or the popen2
module which can handle all the input/output streams.

>>> f = os.popen('prog arg1', 'r')
>>> line = f.readline()
>>> while line:
...   do_something_with(line)
...   line = f.readline()
>>> error_in_prog = f.close()
>>> if error_in_prog:
...   print '"prog arg1" returned with an error code of', error_in_prog

The popen2 module has two functons, popen2 and popen3.  The popen2
function returns two file objects, one to read the output and one to
write input to the program.  The popen3 function returns those two and
the error channel from the program.  But it sounds like the os.popen()
function does what you want.

Python Library Reference, section 6.1.2 File Object Creation
  <URL: http://www.python.org/doc/current/lib/os-newstreams.html>
Python Library Reference, section 6.8 popen2
  <URL: http://www.python.org/doc/current/lib/module-popen2.html>

Good luck.


| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |