Scripting Clinic: Curl Up With Python

Friday Apr 30th 2004 by Carla Schroder

This full-blown interpreted programming language lets you write large, complex programs without having to mess with compiling and linking.

Python is becoming my favorite language for scripting. It's a full-blown interpreted programming language, which means you can write large, complex programs, and don't have to mess with compiling and linking. As overworked, under-appreciated network admins, we're probably more interested in writing nice compact, yet powerful labor-saving scripts, which Python is very good for.

Python has one particular quality that tends to throw new users, especially if they are experienced programmers: Indentation is part of the program logic. Code blocks (functions, conditional statements, and so forth) are defined by their indentation. There are no curly braces or brackets. Indenting starts a block, and unindenting ends it. (Do not mix tabs and spaces, use one or the other exclusively.) This might seem weird, if you're used to using all kinds of punctuation, but it makes for a consistent, readable appearance in all Python scripts and programs, no matter who writes them. And it makes it easy to find code blocks.

The number of spaces does not matter. Most folks use multiples of four; that seems to strike the right balance between readability, and not devoting too much of each line to whitespace.

The Python Interpreter
Like Bash, Python lets you test commands out on the command line before committing them to a script. This opens Python's basic, no-frills command shell:

$ python
Python 2.3.3 (#2, Jan 13 2004, 00:47:05)
[GCC 3.3.3 20040110 (prerelease) (Debian)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

The three angle braces means it is waiting obediently for your command. So let's give it something to do, hit Ctrl+D. Wups! All gone.

Sometimes the program will seem stuck:

>>> somecommand

Python is waiting for some input. If you have nothing to input, hit Ctrl+C to move on:


Python Scripts
The first line in any Python script is

#! /usr/bin/env python

Of course the script must be made executable:

$ chmod +x

Now you can run it like any script or command:

$ ./

Declaring Functions
Functions are the basic building blocks of scripts and programs. Python makes it easy to declare functions. You don't need to declare one until you need it. You don't need header files. And dear to my heart, you don't need to specify a return datatype. That's right, no need to hassle with ints and floats and chars and other horrid things, Python figures out the types for you. You don't need to specify a return value, either. If the function returns a value, Python will print it. If it doesn't, no sweat, it won't. (Technically speaking, it returns a null value.) Use the def keyword to declare a function:

>>> def lamerFunction():

Easy as pie. Any arguments go in the parantheses, separated by commas. End your function declaration with a colon.

Continued on Page 2: Doc Strings

Continued From Page 1

Doc Strings
Python has a built-in documentation tool called "doc string." These are designed to be used by automatic indexing tools, for creating help docs. Doc strings belong to functions, classes, methods, and methods. They immediately follow the header, and are indented, like this:

>>> def lamerFunction():
...        """This is a one-line comment."""

Comments can be as long as needed:

>>> def wicked_kewl_function():
...        """This is a multiline doc string.
...       See, here's the second line.
...       """

This also illustrates Python's two prompts. >>> marks the beginning of a new command. ... is the sub-prompt, which marks all the lines in a command. You have to enter a blank line to get back to the main prompt.

You can read doc strings in the Python interpreter, to find out what a function is for. Note that doc is enclosed by double underlines:

>>> print lamerFunction.__doc__
This is a one-line comment.

>>> print wicked_kewl_function.__doc__
This is a multiline doc string.

      See, here's the second line.

Or, use Python's built-in help:

>>> help(wicked_kewl_function)

Help on function wicked_kewl_function in module __main__:

This is a multiline doc string.

       See, here's the second line.

Hit Q to get out of the help window. So you see, writing detailed, helpful doc strings goes a long ways towards keeping your Python scripts and program understandable, and maintainable.

Python also supports ordinary comments:

# this script written by Awesome Geekasaurus
# for sorting my eleventy-nine zillion pizza recipes

Like any other *nix program, Python has a voracious hunger for over-interpreting strings, which makes using literal strings a real pain in the patootie. How I wish for a simple method to enclose a string containing all kind of quotation marks, forward slashes, backslashes, semi-colons, and everything I want, without having to escape individual characters. My fave is escaping the escape character: \\

OK, whining aside, we're stuck with what we have. Python's method of escaping quotes is just as odd as anyone else's:

>>> 'This is an "example" of using single and "double" quotes in Python.'
'This is an "example" of using single and "double" quotes in Python.'

That's not so bad, is it. Well, remember Bizarro World in the old Superman comics? The planet of people who did everything backwards? I think that's where Python's quoting conventions came from. Sometimes single quotes get turned to double quotes:

>>> 'This is an \'example\' of using single and \'double\' quotes in Python.'
"This is an 'example' of using single and 'double' quotes in Python."

To really have a good time, mix apostrophes and quotes:

>>> 'Let\'s go "nuts" with apostrophes, "quotes", and stuff!'
'Let\'s go "nuts" with apostrophes, "quotes", and stuff!'

Ew, that looks bad. But when you assign the string to a variable and print it, it all comes out right:

>>>speech='Let\'s go "nuts" with apostrophes, "quotes", and stuff!'
>>> print speech
Let's go "nuts" with apostrophes, "quotes", and stuff!

One way to get completely literal strings is with the print command, and triple quotes, like in doc strings:

>>> print """'We have "quote's "single" and 'double' '' and weird "' s'tuff'''"""
'We have "quote's "single" and 'double' '' and weird "' s'tuff'''

How is this useful? Take a look at this if statement:

>>> num = int(raw_input("Please enter an integer: "))
Please enter an integer: -15
>>> if num < 0:
...       print """num is less than zero, and I
...       can use 'quote's" anyway I want
...       'inside' the "triple quotes'
...       """
... else:
...       print """'Eh, it's greater than zero'.
...       '"""
num is less than zero, and I
      can use 'quote's" anyway I want
      'inside' the "triple quotes'

This is not as convenient, perhaps, as having a nice variable to plug in whenever you want to print that particular comment. But it gets the job done.

Next time on Scripting Clinic we'll put together a real live script, and dissect it line-by-line, so you'll understand what the Python bits do, and what role other Linux commands play. Let me know if there's a particular task you'd like to see scripted, preferably something a little more fun than Yet Another Backup Script.

Python is very well-documented, roll on over to and start reading.

Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved