New Python File — TextMate Template

Textmate has the ability to create new files based on a template you create.  It had a few templates for Python, but nothing exactly like I want.

When I start a new python script or module, I want to:

  • Follow the Pythonista style
  • Parse some command line arguments – usually an input file
  • Enable logging (either file based, or to the console)

I created a new TextMate template to do those things.

  1. Select Bundles > Bundle Editor > Show Bundle Editor
  2. Select and Open the Python Bundle
  3. Find the Python Bundle Templtes
  4. Copy one into a new Template.  Give it a sensible name
  5. Replace the text with the following…

Update: You can also grab this code from github!  If you see a way to make it better, please let me know!  Or better yet, fork the code and send me updates.  =)

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

Created by Jerry Steele on 2009-08-12.
Copyright (c) 2009 ACT. All rights reserved.
import os
import sys
import logging
import optparse

LOG = None

def process_command_line(argv):
 Return a 2-tuple: (settings object, args list).
 `argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
 global LOG
 if argv is None:
 argv = sys.argv[1:]

 # initialize the parser object:
 parser = optparse.OptionParser(

 # define options here:
 parser.add_option("-f", "--file", dest="filename",
 help="read data from FILENAME")
 parser.add_option("-v", "--verbose", dest="verbose", default=False,
 action='store_true', help="write debug log to FILENAME")
 parser.add_option("-L", "--log", dest="logfile", help="write debug log to FILENAME")
 parser.add_option(      # customized description; put --help last
 '-h', '--help', action='help',
 help='Show this help message and exit.')

 options, args = parser.parse_args(argv)

 # check number of arguments, verify values, etc.:

 # set up logging
 if options.verbose:
 LOG = setlogging(options.logfile)

 if not options.filename:
 #LOG.error("Input filename not specified")
 #parser.error("You must supply an input file")
 # further process settings & args if necessary

 return options, args

def main(argv=None):
 settings, args = process_command_line(argv)

 # application code here, like:
 # run(settings, args)
 return 0        # success

def setlogging(logfile=None):
 consolelevel = logging.DEBUG
 logger = logging.getLogger(__name__)
 # create formatter and add it to the handlers
 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
 # create console handler with a higher log level
 ch = logging.StreamHandler()
 # add the handlers to logger

 # create file handler which logs error messages
 if logfile:
 filelevel = logging.ERROR
 fh = logging.FileHandler(logfile)

 #test logging
 logger.debug("debug message")"info message")
 logger.warn("warn message")
 logger.error("error message")
 logger.critical("critical message")

 return logger

if __name__ == '__main__':
 status = main()

Even if you don’t use Textmate, you can still use this to quickstart python modules.  Just remove/replace the $TM_ variables

About these ads