klenwell information services : PywellScripts

Revision [2349]

This is an old revision of PywellScripts made by KlenwellAdmin on 2012-12-21 22:11:48.

Pywell Lesson: Scripts

return to PyWell Tutorial Index



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

    Copyright (c) 2012 MIT License: Tom Atwell

# Imports
import sys

# Globals / Constants

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

if __name__ == "__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 called from the command line, 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


Make a copy of the hello.py script named add.py and modify it 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.)


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

Next Lessons: PywellModules Modules, PywellExceptions Exceptions