klenwell information services : PywellScripts

Pywell Lesson: Scripts

return to Tutorial Index

Goals


Lecture

The first thing to know about Python scripts is that Python is whitespace-sensitive. That is: you don't define blocks of code using braces or semi-colons as in many traditional programming languages:

main()
{
    printf("Hello World");
}


You use indentation to define code blocks. As a student of poetry and a neat freak, I like this because it gives Python code a more poetic feel and encourages you to keep your code clean and readable.

Here's a simple Python script:

#!/usr/bin/env python

"""
    Pywell Python Tutorial: Scripts
   
    A basic python script. This is the script's "
docstring". Docstrings are
    a great place to summarize your script or module and include licensing
    information.

    Copyright (c) 2012 MIT License: Tom Atwell
    http://www.opensource.org/licenses/mit-license.php
"
""

#
# Imports
#
import sys


#
# Globals / Constants
#


#
# Main
#
def main():
    args = sys.argv[1:]
    message = "hello %s" % (" ".join(args))
    print message


if __name__ == "__main__":
    main()


The script provides a simple template for your python script. It imports one module from the Python standard library: sys. (More on modules next time.)

Note the if __name__ == "__main__": line at bottom. This is a somewhat idiomatic line that checks to see if the current file is the script being invoked. It says basically, "if this script is being run directly and not imported by another module, run what follows."

Copy and paste that into a text file and save it as hello.py somewhere on your computer -- say your tmp dir. Now your can run it from your terminal by typing python followed by the file path. For example (make sure to adjust path if you used a different one):

python /tmp/hello.py


Now try these:

python /tmp/hello.py world
python /tmp/hello.py planet earth


The sys module provides one very useful attribute: sys.argv. This is a list of command line arguments, beginning with the script path. When you run python /tmp/hello.py planet earth, the sys.argv arguments are: ['/tmp/hello.py', 'planet', 'earth'].

So sys.argv[1:] uses slice notation ([1:]) to say: give me all the command line arguments except the first one (or script path). More on slice notation when we get to lists and sequences.


Exercise

Make a copy of the hello.py script named add.py and modify it to add a series of numbers from the command line like so:

python /tmp/add.py 1 2 3



Extra Credit

  1. Modify your script to interactively prompt the user (you) to enter a list of numbers to add. (See documentation for raw_input function.)


References


* Note documentation version may differ from version of Python you're using.