Bulbul's Python TipsCaveat: I am not a professional programmer. I do this as a hobby. The following notes are strategies which i have either laboured to discover on my own, or found through my readings, in which case there will be due ackowledgements. I welcome constructive comments and criticism. E-mail me at bulbul@ucla.edu. |
Detecting FormsIf your HTML uses both the 'GET' and 'POST' methods, it is important to detect which request method is used before calling cgi.FieldStorage(), because calling that method will fail to return a value (i.e., get stuck in an infinite loop) if the 'GET' method is used with an empty query string. The cgi.FieldStorage() method will not exhibit this undesired behaviour even when the form is empty. Therefore, code similar to the following should do the trick:# This code sets the variable "form" to None when the form is non-existent or empty, |
Adding a Missing string.replace FunctionThe Python 1.4 string module lacks the replace( str, old, new [, max]) function. The following code adds it to the imported string module just in case it isn't there:import string # Of course, don't import string again if you've already done so. |
Change in the Syntax of append()Somewhere between versions 1.5 and 2.2 there has been a change in the syntax of the append method of a list. You can no longer append an arbitrary number of arguments to a list, so you can no longer do numberlist.append( 1, 2, 3 ). Instead you have to append() each item separately or use the + operator.This fact is easy to discover in most scripts, but it can lead to mysterious failures in CGI scripts which used to work, where such an error is harder to pinpoint. (Two hours of my life i could have spent otherwise.) |
Using os.path.walk()I hate the fact that there's no example in the standard documentation on how to use os.path.walk(path, visitfunct, arg). I've written a little example in the form of a program that recursive calculates the size of a directory. View it here: dirsize.py. To check the size of the current directory, just type dirsize.py. To check a different directory, type dirsize.py dirname, substituting the directory name. |
|
Last updated June 18, 2005.
|