Python recipes
From Wildsong
Tips and tricks
Simple file reader
with open(filename) as fp: for line in fp.readlines(): line = line.rstrip("\r\n") # remove trailing newline line = line.lstrip(" \t") # remove leading whitespace if not len(line): continue # skip blank lines # do stuff here
Writing a log
Date stamps
import time
Running commands
import subprocess try: retcode = subprocess.call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e