Cover V12, i12

Article
Figure 1
Sidebar

dec2003.tar

How to Handle (a) Python

Most modern Unix distributions include Python, and good binary and source versions are available from http://python.org/download for essentially all platforms that appear in the pages of Sys Admin.

Bring up a (shell) command line, therefore, and try:

# python
With any luck, you'll see:

Python 2.3+ (#2, Aug 10 2003, 11:33:47)
[GCC 3.3.1 (Debian)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Don't worry if your version is different from this one. The Python language is quite conservative; plenty of applications written in the mid-'90s work unchanged today, and all the experiments described here are compatible with all Python releases dating back several years.

You can use Python in any of a handful of "modes". Most immediately rewarding is the interactive one begun by the command-line invocation above. Treat this as a "calculator":

>>> # Lines that begin this way are comments.
...
>>> # When you type in what appears 
    # after ">>> ", you
...
>>> # should see these results:
...
>>> 2 + 3
5
>>> '2' + '3'
'23'
>>> alphabet = 'abcdefghijklmnopqrstuvwxyz'
>>> character_list = list(alphabet)
>>> character_list.reverse()
>>> reverse_alphabet = ''.join(character_list)
>>> print reverse_alphabet
zyxwvutsrqponmlkjihgfedcba
Python also lets you "batch" your computations. If you create a file called my_script.py with contents:

2 + 3
'2' + '3'
alphabet = 'abcdefghijklmnopqrstuvwxyz'
character_list = list(alphabet)
character_list.reverse()
reverse_alphabet = ''.join(character_list)
print reverse_alphabet
you can run it "automatically" by invocation at the command line of python my_script.py. Executing it yields the output you'd expect:

5
23
zyxwvutsrqponmlkjihgfedcba
As we pursue our work with Python, we'll come across at least a couple of other execution "modes". Interactive and batch interpretation are much the most important for your start. Even if you are accustomed to work with command-line BASIC or Unix shells, though, it's likely to take a while to appreciate the richness of Python's interaction.

Python embeds powerful documenting and introspective capabilities that make it inviting, for example, to "ask the language" itself how common tasks are done. If you're fuzzy on how Python lists work, start by printing out the interpreter's own help on the subject:

# python
Python 2.2.1 (#1, Aug 30 2002, 12:15:30)
[GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help(list)
Help on class list in module __builtin__:

class list(object)
 |  list() -> new list
 |  list(sequence) -> new list initialized from sequence's items
 |
 |  Methods defined here:  ...
Future articles will give more practice in taking advantage of Python's self-documenting benefits.