15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

from the interactive interpreter so that you can observe how system() works.<br />

>>> import os<br />

>>> result = os.system('cat /etc/motd')<br />

Have a lot of fun...<br />

>>> result<br />

0<br />

>>> result = os.system('uname -a')<br />

Linux solo 2.2.13 #1 Mon Nov 8 15:08:22 CET 1999 i586 unknown<br />

>>> result<br />

0<br />

You will notice the output of both commands as well as the exit status of their execution, which we<br />

saved in the result variable. Here is an example executing a DOS command:<br />

>>> import os<br />

>>> result = os.system('dir')<br />

Volume in drive C has no label<br />

Volume Serial Number is 43D1-6C8A<br />

Directory of C:\WINDOWS\TEMP<br />

. 01-08-98 8:39a .<br />

.. 01-08-98 8:39a ..<br />

0 file(s) 0 bytes<br />

2 dir(s) 572,588,032 bytes free<br />

>>> result<br />

0<br />

14.5.2. os.popen()<br />

The popen() function is a combination of a file object and the system() function. It works in the same<br />

way as system() does, but in addition, it has the ability to establish a one-way connection to that<br />

program and then to access it like a file. If the program requires input, then you would call popen() with<br />

a mode of 'w' to "write" to that command. The data that you send to the program will then be received<br />

through its standard input. Likewise, a mode of 'r' will allow you to spawn a command, then as it writes<br />

to standard output, you can read that through your file-like handle using the familiar read*() methods of<br />

file object. And just like for files, you will be a good citizen and close() the connection when you are<br />

finished.<br />

In one of the system() examples we used above, we called the Unix uname program to give us some<br />

information about the machine and operating system we are using. That command produced a line of<br />

output that went directly to the screen. If we wanted to read that string into a variable and perform<br />

internal manipulation or store that string to a log file, we could, using popen(). In fact, the code would<br />

look like the following:<br />

>>> import os<br />

>>> f = os.popen('uname -a')<br />

>>> data = f.readline()<br />

>>> f.close()<br />

>>> print data,<br />

Linux solo 2.2.13 #1 Mon Nov 8 15:08:22 CET 1999 i586 unknown

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!