parsed.org

Tips by tag: python

Add this to your .vimrc:

autocmd FileType python set omnifunc=pythoncomplete#Complete
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd FileType html set omnifunc=htmlcomplete#CompleteTags
autocmd FileType css set omnifunc=csscomplete#CompleteCSS
autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
autocmd FileType c set omnifunc=ccomplete#Complete

Try it out:

$ touch index.html
$ vim index.html
type: <ht[CTRL-X][CTRL-O]
autocompleteccsshtmljavascriptphppythonvimvimrcxml
Automatic Traceback Formatting by cygnus on Aug 07, 2005 10:14 PM

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
Colorize python source in a terminal by cygnus on Jan 12, 2005 10:10 AM

Use the pycolor tool included with ipython. It will format the source using ASCII codes so it looks pretty in your terminal:

$ pycolor foo.py
asciicommandsipythonlanguagesprogrammingpycolorpythonterminal

In Python you can use the array module to quickly convert ASCII values to a string and back again.

>>> import array
>>> array.array('B', [97, 98, 99]).tostring()
'abc'
>>> array.array('B', 'abc').tolist()
[97, 98, 99]

For more information, read Python Patterns - An Optimization Anecdote.

arraysasciiconversionmodulesoptimizationpython
Create Directories Cleanly by cygnus on Jan 24, 2005 09:24 AM

os.mkdir raises a generic exception if an error occurs, but typically you need to ignore preexisting directory errors. Here's how to ignore them:

import os, errno, sys

myPath = "/path/to/dir"
try:
    os.mkdir(myPath)
except Exception, e:
    code, st = e
    if code != errno.EEXIST:
        st = "Error creating directory '%s': %s" % (myPath, str(e))
        sys.exit(1)
directoryexceptionslanguagesmkdirosprogrammingpython
Dynamic Docstrings by Hawk-McKain on May 05, 2008 12:02 AM

Apparently Python only recognizes a doc string a litteral string placed after a function definition, meaning it won't accept an interpolated string, or even 'a'+'b', for whatever reason. For example:

>>> def doc():
...     '''Useful info. Note: %s''' % 'You'll never see this.'
...     print doc.__doc__
>>> doc()
None

To work around this you must explicitly set __doc__. Example:

>>> def doc():
...     doc.__doc__ = '''Useful info. Note: %s''' % 'Bacon is yummy!'
...     print doc.__doc__
>>> doc()
Useful info. Note: Bacon is yummy!
docstringpythonsemanticsstringssyntax
Flatten Lists by Hawk-McKain on Sep 02, 2007 04:17 AM

Flattens a list of any depth:

def flatten(seq, a = []):
    """flatten(seq, a = []) -> list

    Return a flat version of the iterator `seq` appended to `a`
    """

    if hasattr(seq, "__iter__"):  # Can `seq` be iterated over?
        for item in seq:          # If so then iterate over `seq`
            flatten(item, a)      # and make the same check on each item.
    else:                         # If seq isn't an iterator then
        a.append(seq)             # append it to the new list.
    return a
dataflattenlistspython
Globbing by xinu on Feb 08, 2005 12:27 PM

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
Inserting Binaries with Psycopg by xinu on Jan 12, 2005 01:41 PM

Use the psycopg.Binary() function to escape the binary data:

>>> db = psycopg.connect("dbname=%s user=%s" % (database, user))
>>> db.autocommit(True)
>>> cursor = db.cursor()
>>> file = "/path/to/binary_file.jpg"
>>> fd = open(file, "r")
>>> contents = fd.read(os.stat(file)[6])
>>> fd.close()
>>> cursor.execute("INSERT INTO pr0n (image) VALUES (%s)", (psycopg.Binary(contents)))
binarybyteacursordbapiescapeinteractivelanguagespostgresqlprogrammingpsycopgpython
os.system and Broken Pipes by cygnus on Dec 31, 2005 04:08 PM

If you're using os.system to run a command (such as xterm running man) and you get "broken pipe" errors, you can restore standard pipe functionality with the signal module:

import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)

# Call os.system after calling signal.signal.

Note: information taken from http://monkeyfingers.org/ (page now unavailable).

brokenlanguagesospipeprogrammingpythonsignalsystemunix
Path Calculation by xinu on Mar 30, 2007 01:13 PM

If you need to tell a python framework where your templates, etc. are located, it helps to determine the location of the current module.

BASE_PATH = os.path.abspath(os.path.join(os.path.dirname(__FILE__), '..'))
TEMPLATES = os.path.join(BASE_PATH, 'templates')

Assuming you're running this code in /path/to/module.py, BASE_PATH will be set to /path. Other os.path tricks can be used to dynamically set paths in this way.

locationosparsingpathpython
Print Without Trailing Newline by cygnus on Aug 17, 2005 01:26 PM

To make print suppress its usual trailing newline, add a comma to the end of the statement:

print "Foo",
print "Foo %s" % (bar),
languagesprintprogrammingpythonsyntaxtrailing-newline
Psycopg1 Compatibility Mode by cygnus on Dec 31, 2005 04:07 PM

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 Duplicates by xinu on Jan 13, 2005 08:50 AM

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

Use this elisp snippet (in your ~/.emacs) to instruct your Emacs python-mode to use the proper python executable on a system with multiple pythons installed:

(setq py-python-command "/usr/bin/python2.3")
dotemacselispemacsinterpreterinvocationlanguagesprogrammingpython
Using a Generator to Build Text by cygnus on Dec 31, 2005 04:07 PM

If you need a function to build a big block of text and return it at the end, you may be concatenating all of the pieces of text into one big string. Rather, you can use a generator to return the text cleanly and efficiently:

def buildText():
    yield "This is the first line."
    for i in range(10):
        yield "Line %d" % (i)
    yield "This is the last line."

Then, you can automatically build a list of the generator's results:

results = list(buildText())

(To learn more about generators, see "the python tutorial" at http://docs.python.org/tut/node11.html#SECTION00111000000000000000000.)

efficiencygeneratorslanguagesprogrammingpython
RSS