How to create a basic program in Python

Up until now, you've been using the Python interpreter mainly in interactive mode. For production use, you'll want to create Python programs or scripts. If you come from a Linux/UNIX background, you may be familia...
This article was sent to us by: Kyle D. at 01052010

1 Programming » How to create a basic program in Python
Bookmark and Share

Up until now, you've been using the Python interpreter mainly in interactive mode. For production use, you'll want to create Python programs or scripts. If you come from a Linux/UNIX background, you may be familiar with scripts that can be started from a command line and given arguments and options that can be used to pass in information and possibly redirect their input and output. If you're from a Windows or Mac background, these things may be new to you, and you may be more inclined to question their value. It's true that command-line scripts are less convenient to use in a GUI environment, but the Mac now has the option of a UNIX command-line shell, and Windows also offers enhanced command-line options. You may find occasions when these techniques are useful, or you may run across code that you need to understand that uses some of them. In particular, command-line techniques are very useful when you need to process large numbers of files.

Any group of Python statements placed sequentially in a file can be used as a program, or script. But it's more standard and useful to introduce additional structure. In its most basic form, this is a simple matter of creating a controlling function in a file and calling that function. In a script, main is our controlling-and only-function. It's first defined, and then it's called. Although it doesn't make much difference in a small program, using this structure can give you more options and control when you create larger applications, so it's a good idea to make it a habit from the beginning. If you're using Linux/UNIX, make sure Python is on your path and you're in the same directory as your script. Then type the following on your command line to start the script: python script1.py. If you're using a Macintosh computer running OS X, the procedure is the same as for other UNIX systems. You need to open a terminal program, which is in the Utilities folder of the Applications folder. There are several other options for running scripts on OS X, which we'll discuss shortly. If you're using Windows, open Command Prompt (in the Accessories subfolder of the All Programs folder in the Start menu). This opens in your home folder, and if necessary you can use the cd command to change to a subdirectory. A simple mechanism is available for passing in command-line arguments. You can see that the command-line arguments have been stored in sys.argv as a list of strings. You can redirect the input and/or the output for a script using command-line options. This script reads its standard input and writes to its standard output whatever it read, with all occurrences of its first argument replaced with its second argument.

Called as follows, it will place in outfile a copy of infile with all occurrences of zero replaced by 0. Note that this will work on UNIX; but on Windows, redirection of input and/or output will work only if you start a script from a command prompt window. In general, the line will have the effect of having any input or sys.stdin operations directed out of infile and any print or sys.stdout operations directed into outfile. The effect is as if you set sys.stdin to infile with 'r' (read) mode and sys.stdout to outfile with 'w' (write). This line causes the output to be appended to outfile rather than overwrite it, as happens in the previous example. You can also pipe in the output of one command as the input of another command. This results in outfile containing the contents of infile, with all occurrences of 0 changed to zero and all occurrences of 1 changed to one. You can configure a script to accept command-line options as well as arguments. The optparse module provides support for parsing different types of options and arguments and can even generate usage messages. To use the optparse module, you create an instance of OptionParser, populate it with options, and then read both the options and the arguments. This adds a filename option with either '-f' or '-file'. The final option added, the "quiet" option, also adds the ability to turn off the verbose option, which is True by default (action=store_false). The parse_args method returns two objects: one containing the options and their values as key/value pairs, and a list of the positional arguments. You can get the values of the options from the first object by using the string you specified with the dest parameter as a dictionary key. If there's no argument for an option, the value is None. Any elements left on the command line after all the options have been parsed will be in the list of positional arguments.

The fileinput module is also sometimes useful for scripts. It provides support for processing lines of input from one or more files. It automatically reads the commandline arguments (out of sys.argv) and takes them as its list of input files. It allows you to then sequentially iterate through these lines. We obtain the following result with the comment lines stripped out and the data from the two files combined. If no command-line arguments are present, the standard input is all that is read. If one of the arguments is a hyphen (-), the standard input is read at that point. The module provides a number of other functions. These allow you at any point to determine the total number of lines that have been read (lineno), the number of lines that have been read out of the current file (filelineno), the name of the current file (filename), whether this is the first line of a file (isfirstline), and/or whether standard input is currently being read (isstdin). You can at any point skip to the next file (nextfile) or close the whole stream (close). Finally, if you call fileinput.input with an argument of a single filename or a list of filenames, they're used as its input files rather than the arguments in sys.argv. fileinput. input also has an inline option that leaves its output in the same file as its input while optionally leaving the original around as a backup file. See the documentation for a description of this last option.

Legal Disclaimer

Our website is not responsible for the information contained by this article. Articleinput.com is a free articles resource thus practically any visitor can submit an article. However if you notice any copyrighted material, please contact us and we will remove the article(s) in discussion right away.

Related Articles

1. How to make Python script execution in UNIX and Mac OS X and in Windows
If you're on UNIX, you can easily make a script directly executable. Note that if Python 3.x isn't your default version of Python, you may need...

2. The difference between scripts on Windows scripts on UNIX
The way you call scripts on Windows differs from the way scripts are called on Linux/ UNIX, and that difference can affect what kind of scripts...

3. Python applications are distributed as source files
You can distribute your scripts as source files (as .py files). You can also ship them as byte code (as .pyc or .pyo files). A byte code file w...

4. How to use the Python file system
Working with files involves one of two things: basic I/O and working with the filesystem (for example, naming, creating, moving, or referring t...

5. Client complaints about inconsistent query results
You've probably seen it before: a client has called the help desk and reported that a couple of queries have seemingly inconsistent results. Yo...

6. How to ensure data quality
The most fundamental thing you can do to ensure the quality of your data is to choose a reasonable container for the value being stored. Want t...

7. How to use a foreign key constraint
A foreign key constraint is used to make sure that columns involved in a relationship contain only correct data. I start out the article with a...

8. Triggers in SQL Server programming
Triggers are stored batches of T-SQL, much like stored procedures. But instead of being called directly, they execute indirectly when you execu...