Add the following code to the top of a CGI Python script to enable colorized, annotated traceback formatting whenever a fatal error occurs in your script:
import cgitb; cgitb.enable()
When in development mode, this is likely more helpful than a '500 Internal Server Error'.
cgicolorerrorsfatalimportlanguagesmodulesprogrammingpythonscripttraceback
An often-used concept in shell scripting is globbing. You can use this in python, as well:
import glob
for textFile in glob.glob("*.txt"):
# Do something with 'textFile'.
globimportlanguagesmodulesprogrammingpythonshell
To create a new project with its own repository, do this. The svnadmin command assumes the path exists already:
$ svnadmin create /path/to/repository $ svn import project_name file:///path/to/repository -m 'initial checkin'
Then remove the original copy and check it out:
$ mv project_name project_name.old $ svn checkout file:///path/to/repository/trunk project_name
Note: You can change the file:// to svn:// or whatever protocol you're using.
commandsimportprojectsubversionsvnsvnadmin
If you're using the psycopg Python module to connect to Postgres, you may find that you have old scripts that use version 1 of psycopg but you have version 2 installed and don't want to modify your scripts. At the time of this writing (and according to http://initd.org/tracker/psycopg/wiki/Migration), the version 2 module provides a very easy "compatibility mode". Just import the psycopg1 submodule and alias it, or fall back to the version 1 module if version 2 is not available:
try:
# Try importing the compatibility submodule, which will only
# work if psycopg version 2 is available.
import psycopg.psycopg1 as psycopg
except Exception, e:
# Fall back to version 1.
import psycopg
aliasdbapiimportlanguagespostgresqlprogrammingpsycopgpsycopg2python
Remove duplicate elements from a list:
newList = dict([(item, 1) for item in oldList]).keys()
Or, if you have Python 2.3 or newer, you can use a Set object to collapse your list:
import sets newList = list(sets.Set(oldList))
dataimportlanguagesprogrammingpythonsetsyntax