how to get output from system call into data object

Donn Cave donn at u.washington.edu
Fri Aug 27 13:12:12 EDT 1999


Quoth stephen at tocol.chc.us.ac.com (Stephen M. Shelly):
| ... I need to run
| a command which will return data in column format, I want to extract 
| particular columns into data structures that I can then manipulate.
| I currently have:
| import os
| system("my_command | awk {'print $What $I $ Need'}")
|  i would like to fill a list of objects with this output, but I 
| do not know how......

Awk processes its input in terms of white space separated fields, and
with luck that may work for columns.  Its output puts those fields
back together, though.  If your Python program needs columns, it's
going to do this work itself, so you might as well skip awk and do
the work in python.

    import os   # or posix
    import string
    file = os.popen(my_command, 'r')
    while 1:
        line = file.readline()
        if not line:
            break
        columns = string.split(line)
        # Now you have to sort out which column is which.
    status = file.close()
    if status:
        status = status >> 8
        print my_command, 'exited with abnormal status', status

Incidentally, you must be very careful with the commands you execute
with popen() and system().  They're interpreted by the UNIX shell, and
have the potential to execute any command on the computer, by an
accident of punctuation.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu




More information about the Python-list mailing list