Up

Contents

import pydoc
pydoc.gui()

To run a command and capture its output

import commands
print commands.getoutput('hostname')

Easy Python Here Documents

Here is some sample code:

#!/usr/bin/env python
# encoding: utf-8

name="The President"
address=1600
street="Pennsylvania Avenue"

print """\
%(name)s lives at %(address)05d %(street)s""" % locals()

Here is the output:

The President lives at 01600 Pennsylvania Avenue

Building a Simple extension on Mac OS X

Here is the source code hello.c:

#include <Python.h>
#include <string.h>
static PyObject *
message(PyObject *self, PyObject *args )
{
	char * fromPython, result[64];
	if (!PyArg_Parse(args, "(s)", &fromPython))
		return NULL;
	else {
		strcpy( result, "Hello, ");
		strcat( result, fromPython );
		return Py_BuildValue("s", result);
	}
}

static struct PyMethodDef hello_methods[] = {
	{"message", message, 1},
	{NULL,NULL}
};

void inithello()
{
	(void)Py_InitModule("hello", hello_methods);
}

Here is the Makefile. Note that you may have to change the PYINC path to match your Python installation

PYINC = "/Library/Frameworks/Python.framework/Versions/Current/include/python2.5"

CC = cc
LD = cc
CFLAGS = -O -fno-common

all: hello.so

hello.o: hello.c
	$(CC) $(CFLAGS) -I$(PYINC) -c hello.c

hello.so: hello.o
	$(LD)  -dynamiclib  -framework Python  -o hello.so hello.o

clean:
	rm hello.o hello.so

Build your extension:

make

Test the result:

python
>>> import python
>>> python.message("bob")
'Hello, bob'

Building and Installing a C Python extension using distutils on Mac OS X

OK, start with the same hello.c file as before. Create a file in the same directory called setup.py as follows:

from distutils.core import setup, Extension

module1 = Extension('hello',
                    sources = ['hello.c'])

setup (name = 'Hello',
       version = '1.0',
       description = 'This is a demo package',
       ext_modules=[module1]
    )

Build your extension as follows:

python setup.py build

Install your module as follows:

sudo python setup.py install

Really cool! See here for more info.

Partial functions in Python

This is a really handy feature. Here is a snippet of code that came from the comp.lang.python newsgroup. It was posted by Christopher King on 2004-06-25:

def partial(func,*args,**kw): 
    return lambda *a,**k: func(*(args+a),**dict(kw.items()+k.items())) 

Here is a trivial example of its use:

def f(x,y):
    print "F: x=%d, y=%d, x+y=%d" % (x,y,x+y)

p1 = partial(f,1)
p2 = partial(f,10)

p1(1)
p2(1)

Here is the output of this:

F: x=1, y=1, x+y=2
F: x=10, y=1, x+y=11

If you are running Python 2.5 then this functionality is already built-in. A module called functools defines a partial class that does the same thing (and probably more). Here is a Python 2.5 example:

from functools import partial
def f(x,y):
    print "F: x=%d, y=%d, x+y=%d" % (x,y,x+y)
p1 = partial(f,1)
p2 = partial(f,10)

p1(1)
p2(1)

The output is the same.

The nifty Python csv module

Here are two small sample input files:

1.csv

a,b,c
d,"e&f",g

2.csv

a       b       c
d       e&f     g

1.csv is comma/quote delimited and 2.csv is TAB-delimited.

Here is a small program test_csv.py

import csv
print 'first example -- we specify the delimiter and quoting'
files = {'1.csv' : {},
         '2.csv' : {
                 'delimiter' : "\t",
                 'quoting' : csv.QUOTE_NONE
             }
         }
for f,o in files.iteritems():
    print "reading file %s" % f
    reader = csv.reader(open(f, "rb"), **o)
    for row in reader:
        print row

print 'second example -- we sniff the file first'
sniffer = csv.Sniffer()
for f in files:
    print "sniffing file %s" % f
    fl = open(f,"rb")
    d = sniffer.sniff(fl.readline())
    fl.seek(0)
    reader = csv.reader(fl, d)
    for row in reader:
        print row

Here is the output from the program:

$ python test_csv.py 
first example -- we specify the delimiter and quoting
reading file 2.csv
['a', 'b', 'c']
['d', 'e&f', 'g']
reading file 1.csv
['a', 'b', 'c']
['d', 'e&f', 'g']
second example -- we sniff the file first
sniffing file 2.csv
['a', 'b', 'c']
['d', 'e&f', 'g']
sniffing file 1.csv
['a', 'b', 'c']
['d', 'e&f', 'g']


Page last modified on August 28, 2008, at 01:05 PM