Python recipes

From Wildsong
Revision as of 19:44, 2 December 2015 by Brian Wilson (talk | contribs)
Jump to navigationJump to search

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