See All Titles |
![]() ![]() ProgramsUntil now, all the examples were written directly in the interpreter environment. However, most Python programs are executed as external scripts, being loaded from files. You can write your own Python scripts by using any text editor of your choice. Remember to always save your files using the .py extension. As with any other UNIX scripting language, Python scripts (for UNIX) need a special handling. First, you need to put a "shebang" in the first line of the script. This line declares the location of Python's interpreter in your system. For example #!/usr/local/bin/python Note that this example works only if Python was installed under the given mounting point. Most Linux systems have Python installed under /usr by default, so the preceding example will not work. Today, the following line of code seems to be more common, and does not depend on where Python is installed: #!/usr/bin/env python If you are running your scripts on an MS Windows environment, you can keep this line of code for portability purposes because the literal # is only used to identify comment lines that are ignored by the interpreter, so it will cause no harm to your programs. If you don't know where Python is located on your UNIX system, use the following command: $ whereis python Also, remember to set the permissions on your script to 755 in order to let every user be able to execute it. $ chmod +x scriptname.py or $ chmod 755 scriptname.py As you cannot directly execute Python scripts in the MS Windows systems through the command line, you have two options: Either double-click the file using Windows Explorer or call the interpreter, passing the filename as an argument. For example, c:\>python scriptname.py Another way to call the interpreter on Windows systems is by typing start scriptname.py at the shell prompt. This command will find and execute the program associated with the extension .py. If you want to open the interpreter after executing a program, use the -i argument when calling the script. The interpreter will run your script, and after it executes all the commands, it will open its command-line interface for you. Here's how to call the script with a command-line option: c:\python -i scriptname.py Otherwise, after the script finishes its execution, it will automatically close the interpreter. After spending some time creating Python programs, you might find some .pyc files in the same directory in which you are saving your .py scripts. See Chapter 17, "Development Tools," to know more about this other file extension. IndentationPython delimits code blocks by using indentation. There is no concept of {}s or Begin/Ends as in other languages. When you indent a block of code, you define the way the statements are grouped. It also reduces errors due to bad indentation. For instance, the following C or Perl code looks like a single if statement, but the second statement is always executed: if (expression) statement1; statement2; Python doesn't suffer from this problem because indentation defines block structure. Another great aspect of this implementation is that you can reduce the size of your code while using indentation instead of conventional block delimiters. Tip
Keep in mind that tabs are internally converted to spaces (1 tab = 8 spaces), and blank lines are ignored when part of scripts. I suggest you write one statement per line, using a newline (ENTER) to terminate each line. If you decide to have more than one statement in the same line, you need to separate them by using semicolons, as shown in the following: >>> print "When AH "; print "were young…" Remember that you must put a backslash \ at the end of lines that need to be broken into two lines: >>> t = "Nobody expects " + \ … "the Spanish inquisition" Lexical AnalysisIt is unnecessary to declare the type of a variable in Python programs. The same variable name might have different types at different occasions because it is re-initialized every time a value gets assigned to it, as illustrated in the following: >>> x = "Albatross!!" >>> print x Albatross!! >>> x = 123 >>> print x 123 You can assign any object type to a variable (for example, functions, classes, and modules). The following example shows how you can create a variable that references the round() function object: >>> x = round >>> print x(27.234523, 2) 27.23 You don't have to worry about deallocating variables in Python. Python objects are collected whenever they become unreachable because Python does reference counting. This means that as long as there is a reference to an object, the object isn't collected. When you delete a reference to an object, its reference counting goes down by one, and when the count has dropped to 0, it is eligible for garbage collection. Note that under CPython, objects are deallocated as soon as the reference count reaches 0. The problem with reference counting is that you can create circular references, such as the following: >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> a.append(b) >>> a [1, 2, 3, [4, 5, 6]] >>> b.append(a) >>> a [1, 2, 3, [4, 5, 6, […]]] >>> b [4, 5, 6, [1, 2, 3, […]]] >>> del a >>> del b Now, you can never refer to variables a and b, nor to their contents again, and because each one of them is still referenced by the other list, they cannot be collected, either. Note that recursion is indicated by the […] element. I know that it is fairly easy to fall into this trap, and although some work is being done to cure this problem, I strongly suggest that you avoid recursive constructs. As you might notice, del removes the reference to the object, which could cause it to be deallocated if its reference count reaches 0. You can monitor the reference counting of an object by using the sys.getrefcount() function: >>> import sys >>> sys.getrefcount(b) 3 Note that you can break the circular reference if you insert the following lines between the appends and dels: >>> del a[-1] >>> del b[-1] Actually, we are just breaking the references by removing the […] entries from the lists. Note that the release 2.0 of Python makes sure that deleting objects is safe even for deeply nested data structures. The Python interpreter is now using a new mechanism to collect unused objects. From time to time, this mechanism performs a cycle detection algorithm that searches for inaccessible cycles and deletes the participating objects. This process has been named Garbage Collection of Cycles. There are a couple of parameters of the garbage collection that you can manipulate. The module gc provides functions that helps you out with that. Of course, you always have the option to disable this feature. To do so, simply specify the argument " -without-cycle-gc " when running the Python configure script. Reserved WordsPython has reserved a group of words for its own use. Those words have specific meanings that cannot be changed. You cannot use these words as identifiers in your code. "and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while" IdentifiersPython identifiers are any objects created by programmers (such as variables, classes, and so on). Identifiers can be named using any of the following characters: A-Z, a-z, 0-9, and _. However, they can't start with a digit. You must write your code carefully because Python identifiers are case sensitive. The special characters: $, %, and @, aren't allowed to be part of an identifier's name. Besides that, $ and @ can be used only in a program, inside quoted strings. The % character may be used in a program because it is the mod operator.
|
© 2002, O'Reilly & Associates, Inc. |