Originally Published: Wednesday, 30 August 2000 Author: Jason Tackaberry
Published to: develop_articles_tutorials/Development Tutorials Page: 3/6 - [Printable]

Programming with Python - Part 1: Baby Steps

This tutorial is the first in a series that will introduce you to Python, a dynamic, object-oriented language that is rapidly gaining popularity. Since I myself have garnered a modest Perl background before learning Python, I will target this tutorial at the Perl programmer. However, anyone with a little programming experience should find this text useful.

Doing Something Useful  << Page 3 of 6  >>

Doing Something Useful

Up until now we've mostly been looking at Python's syntax, and learning about the basic building blocks. There's still plenty more to learn about, but at this point we're ready to look at some code that actually does something. Let's look at some code that reads /etc/passwd and prints out a list of users who are in groups whose group id is greater than 100.

  import string

  pwdfile = open("/etc/passwd")
  lines = pwdfile.readlines()
  for entry in lines:
    fields = string.split(entry, ":")
    if int(fields[3]) > 100:
      print fields[0]

Only a few select functions are built into Python's core. In order to do something useful, you'll need to use one or more modules. Python is distributed with a standard library containing a vast number of modules. In the first line, we import the string module, which allows us to perform common string operations. In our example, we're interested in the string module's split function.

After importing the string module, we then open the /etc/passwd file. The open function is a built-in function that returns a file object. File objects are one of the few built-in types. A second optional argument passed to open specifies if the file should be open in read-only, or read-write mode. In the absence of this argument, read-only is assumed. Next, we call the readlines() function of the file object, which returns a tuple whose elements correspond to the lines in the file. Then, in the for loop, we iterate over each of the lines in the lines tuple, which we know corresponds to an entry in the passwd file.

The first line in the for code block calls the string module's split function. Perl coders will know right away what's happening here; this function separates the given string by a separation string, in this case ":", and returns a tuple of all the strings between (but not including) the separation string. Now we have a tuple called fields that holds the individual fields in the passwd entry. The group id is held in the fourth field, which is at index 3 (indices start at 0, like in Perl or C). First we must coerce that field to an integer (because it's a string right now), and do the comparison. If it's greater than 100, we print the user name, which is the first field. "But wait!" the Perl coder exclaims. Why do we have to explicitly convert the string to an integer? In Perl, this is done for you behind the scenes. In Python, you need to do this yourself.

A little bit of shorthand can be used in the above example. In particular, I would write the three lines after the import statement as:

  for entry in open("/etc/passwd").readlines():

One feature of Python is that users needn't worry about freeing memory. Internally, Python objects use reference counting as means of garbage collection. When an object is created, its reference count is initialized to 1. When an object is deleted, its reference count is decremented. When the reference count reaches zero, the object is destroyed. The third tutorial in this series will go into more detail on reference counting. It's more of an implementation detail that you don't need to worry too much about, except that you should be aware that it exists. In the compressed code snippet above, the open call returns a file object that isn't being assigned anywhere. So, internally the reference count of this object is decremented. Since no other objects hold a reference to it, the file object is destroyed and the file is closed.

Doing Something Useful  << Page 3 of 6  >>