«»

Technicality

· 9TH OF MARCH, THE YEAR 2006

LEARNING PYTHON: NOTES FROM A YOY

Tha’ts young-of-the-year, for you non-herpetologist Python coders.

See also:

Control Structures

Ternary/Trinary Operator

…doesn’t exist in Python. You have to do something like this:
>>> 1 == 1 and "all is well" or "logic is broken"
>>> "all is well"

Check out this ASPN page for a little bit more.

Directories & Files

Iterating over files in a directory matching a pattern

import glob

for file in glob.glob('*.tif'):
print file

Do the same, renaming files

import glob
import os

for file in glob.glob('*.tif'):
newfile = file.replace('aubrey', 'maturin')
os.rename(file, newfile)

Making system calls

from os import system
system('ls -lh')

Strings

Stripping punctuation from a string

No handy dandy do everything library of built in string processing functions like PHP, I’m afraid. There’s probably a better way to do this, so if you know it, please tell me!
import string
for char in the_string:
if char in string.punctuation:
the_string.replace(char, '')

Lists & Dictionaries

Arrays are called “lists” in Python, because I guess they’re not entirely arrays, but they’re usually the functional equivalent. Similarly, hashes are called “dictionaries.”

Equivalent of PHP foreach ($arr as $index=>$value)

for index, value in enumerate(arr):

List comprehension

Python has this nifty feature that lets you get the results of applying a function to all members of a list in a single line.
[sentence.strip() for sentence in paragraphList]

Sorting a Dictionary by Value

from operator import itemgetter
d = dict(sorted(d.items(), key=itemgetter(1))

also d = dict(sorted(d.items(), key=lambda(k,v): v))

Database

Querying a PostgreSQL database

I use PostgreSQL, and I like handling my result rows as objects. The latter may be a holdover from PHP, but it still seems like a reasonable and possibly standard piece of functionality to expect from something as supposedly robust as Python. Turns out Pg functionality and object rows were certainly NOT obvious. Of the few Pg interfaces I was able to emerge or easy_install, none of them worked very well, so I settled with Psycopg, which I actually had to install manually. Installation was a cinch, but I shouldn’t have had to do that. That should either be in the Standard Library or ir should be in available and functional in one of the repositories.

Psycopg conveniently has no documentation online. Maybe it’s more ‘Pythonic’ to have your docu in the code, or to provide a bunch of examples with the source, but I think if your project has a website, that web site needs to have at least minimal documentation and/or code examples. I ended up using the examples with the source as a (poor) guide.

As for object rows, what amounts to a single line in PHP required a separate module (dtuple, which I had to go to the Cookbook to discover), again, not in any of the standard repositories, that requires all manner of hoohah to get what I wanted. My final solution, after installing psycopg2 and dtuple:

import psycopg2, dtuple
conn = psycopg2.connect('dbname=my_database user=me')
cursor = conn.cursor()
cursor.execute('select * from my_table')

descr = dtuple.TupleDescriptor(cursor.description)
for row in cursor.fetchall():
row = dtuple.DatabaseTuple(descr, row)
print "First Name: %s" % row.first_name

But wait! Apparently there is some Psycopg documentation online, it’s just buried in their wiki, instead of linked from their front page with a large button that says “Documentation.”

import psycopg2.extras
for row in cursor.fetchall():
print "First Name: %s" % row['first_name']

So sacrifice some pretty object dot notation for some clunkier dictionaries? Might be worth it.

Mac OS X

Python can be pretty sweet for playing around with OS X.

AppleScript Bridge

appscript is a really cool package that provides a Python interface to AppleScript functionality provided by many OS X apps. When you download it, don’t forget to grab the ASDictionary app for generating documentation for the Python versions of AppleScript functions and classes.

Here’s a quick little program for controlling iTunes volume from serial input written by my friend Hannes (in this case serial input was coming from a potentiometer hooked up to an Arduino board):

import serial
from appscript import *
ser = serial.Serial('/dev/tty.usbserial-A4001nKF', 9600)
iTunes = app("iTunes")
def set_volume(volume):
iTunes.sound_volume.set(volume)
while 1:
v = int(ser.readline().strip())
volume = v * 100/1024
set_volume(volume)

Reading plists

Plists are the standard XML-based file format for storing properties in OS X apps. They’re just XML files filled with key/value pairs, but for really lazy people like me, there’s a module called plistlib that makes it super simple to read and write. Here’s an example I snagged from 60 Minutes of MacPython (an interesting talk that seems to have disappeared in its original form)

>>> import plistlib
>>> filename = '/Users/kueda/Library/Safari/Downloads.plist'
>>> plist = plistlib.readPlist(filename)
>>> [dl['DownloadEntryURL'] for dl in plist['DownloadHistory']]
['http://ftp-mozilla.netscape.com/pub/mozilla.org/camino/releases/en-US/Camino-1.5.3.dmg']

NO COMMENTS YET

Comments are closed.