Like shell scripts, python may not be able to do everything you want by itself. You may need to execute an external program to get the job done.

NOTE: This is the old way to call external programs and still valid for python versions 2.3 and earlier. However, if you are using 2.4 or later, then use subprocess. The documentation for subprocess is very flushed out so I will not be expanding on it here.

Python's os module offers loads of ways to accomplish this. I will cover only the ones you are to use when replacing shell scripts.

import os
return_status = os.system('ping -c 5 localhost')

The os.system function is the least useful. I will execute a command as specified and return the return status of the program. This is especially useless on operating systems with inconsistent return statuses, i.g. Windows. Any output from the program will be sent to the standard locations, stdout and stderr.

import os
output = os.popen('ping -c 5 localhost')
print output.read() # Streams are file-like

Perhaps you might want to capture the program's output for later. The os.popen function returns a stream of the output from the program. These streams are handled just like files in python. Use the read and readline methods to access the output. With popen, the function returns immediately, so you can run multiple external programs at once.

import os
stdin, stdout = os.popen2('sed s/p/q/g')
stdin.writelines('Replace the ps with qs please')
stdin.close()
print stdout.readline() # prints Reqlace qs with qs qlease

What if you want to give the program a little input? The os.popen2 function lets you do just that. It returns a file stream to both the stdin and stdout of the program. Just write your input, close the stdin stream, and read the output. There are more popen functions. The os.popen3 returns file streams to stdin, stdout, and stderr. os.popen4 returns two file streams, the stdin and the merged stdout/stderr.

Posted by Tyler Lesmann on January 12, 2009 at 5:51
Tagged as: python shell_scripting
Post a comment