dreamsys software

Python Scripting Tutorial

Shell Scripting


One of the most useful packages for unix shell scripters in python is the subprocess package. The simplest use of this package is to use the call function to call a shell command:

#!/usr/bin/env python
import subprocess
subprocess.call("ls -l", shell=True)

This script will call the unix command "ls -l" and print the output to the console. While this is useful, most of the time you want to process the results of the call inside your script instead of just printing them to the console. To do this, you will need to open the process with the Popen function. The Popen function works a little different than call(), it takes an array containing the process to invoke and its command line parameters. So if we wanted to tail the last 500 lines of a log file, we would pass in each of the parameters as a new element in the array. The following script shows how:

#!/usr/bin/env python
import subprocess

proc = subprocess.Popen(['tail', '-500', 'mylogfile.log'], stdout=subprocess.PIPE)

for line in proc.stdout.readlines():
    print line.rstrip()

This script will open the process on unix "tail -500 mylogfile.log", read the output of the command and print it to the console.

The first thing the script does is create a variable "proc", this is the process object returned by the call to subprocess.Popen. In the call to Popen, it passes the 3 arguments to call the tail command (the command itself and the 2 command line arguments) as a single array, then it sets the "stdout" variable of the process to subprocess.PIPE, which means that it will pipe the output back to your script via the "proc.stdout" variable. From there it loops through calling readlines() and prints each line to the console. You will also notice it calls rstrip() on the line, this is a trim function that trims any whitespace, including returns, from the right side of the string. This is done because readlines() returns the string with a return character at the end of it, and print already prints a return.

I hope you have enjoyed this tutorial introduction to python.

Prev (Enums) | Next (TOC)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6