Python Programming For Beginners



Getting Started

To begin, if you have not installed the Python interpreter on your system, now is the time. To make that step easier, install the latest Python distribution using packages compatible with your Linux distribution. rpm, deb and tgz are also available on your Linux CD-ROM or on-line. If you follow standard installation procedures, you should not have any problems.

I also recommend that you have the Python Library Reference handy; you might want it when the explanations given here do not meet your needs. You can find it in the same places as the Python Tutorial.

Creating scripts can be done using your favorite text editor as long as it saves text in plain ASCII format and does not automatically insert line breaks when the line is longer than the width of the editor’s window.

Always begin your scripts with either

#! /usr/local/bin/python


#! /usr/bin/python

If the access path to the python binary on your system is different, change that line, leaving the first two characters (#!) intact. Be sure this line is truly the first line in your script, not just the first non-blank line-it will save you a lot of frustration.

Use chmod to set the file permissions on your script to make it executable. If the script is for you alone, type chmod 0700; if you want to share it with others in your group but not let them edit it, use 0750 as the chmod value; if you want to give access to everyone else, use the value 0755. For help with the chmod command, type man chmod.

Reading Command-Line Options and Arguments

Command-line options and arguments come in handy when we want to tell our scripts how to behave or pass some arguments (file names, directory names, user names, etc.) to them. All programs can read these options and arguments if they want, and your Python scripts are no different.

Implementing appropriate handlers boils down to reading the argv list and checking for the options and arguments you want your script to recognize. There are a few ways to do this. Listing 1 is a simple option handler that recognizes common -h, -help and –help options, and when they are found, it exits immediately after displaying the help message.[source]-