Merge branch 'master' into subfolders-8.3
[pyTivo.git] / Cheetah / TemplateCmdLineIface.py
blobabd8ae259c5098664bad293aa4da523a78590a66
1 #!/usr/bin/env python
2 # $Id: TemplateCmdLineIface.py,v 1.13 2006/01/10 20:34:35 tavis_rudd Exp $
4 """Provides a command line interface to compiled Cheetah template modules.
6 Meta-Data
7 ================================================================================
8 Author: Tavis Rudd <tavis@damnsimple.com>
9 Version: $Revision: 1.13 $
10 Start Date: 2001/12/06
11 Last Revision Date: $Date: 2006/01/10 20:34:35 $
12 """
13 __author__ = "Tavis Rudd <tavis@damnsimple.com>"
14 __revision__ = "$Revision: 1.13 $"[11:-2]
16 import sys
17 import os
18 import getopt
19 import os.path
20 try:
21 from cPickle import load
22 except ImportError:
23 from pickle import load
25 from Cheetah.Version import Version
27 class Error(Exception):
28 pass
30 class CmdLineIface:
31 """A command line interface to compiled Cheetah template modules."""
33 def __init__(self, templateObj,
34 scriptName=os.path.basename(sys.argv[0]),
35 cmdLineArgs=sys.argv[1:]):
37 self._template = templateObj
38 self._scriptName = scriptName
39 self._cmdLineArgs = cmdLineArgs
41 def run(self):
42 """The main program controller."""
44 self._processCmdLineArgs()
45 print self._template
47 def _processCmdLineArgs(self):
48 try:
49 self._opts, self._args = getopt.getopt(
50 self._cmdLineArgs, 'h', ['help',
51 'env',
52 'pickle=',
55 except getopt.GetoptError, v:
56 # print help information and exit:
57 print v
58 print self.usage()
59 sys.exit(2)
61 for o, a in self._opts:
62 if o in ('-h','--help'):
63 print self.usage()
64 sys.exit()
65 if o == '--env':
66 self._template.searchList().insert(0, os.environ)
67 if o == '--pickle':
68 if a == '-':
69 unpickled = load(sys.stdin)
70 self._template.searchList().insert(0, unpickled)
71 else:
72 f = open(a)
73 unpickled = load(f)
74 f.close()
75 self._template.searchList().insert(0, unpickled)
77 def usage(self):
78 return """Cheetah %(Version)s template module command-line interface
80 Usage
81 -----
82 %(scriptName)s [OPTION]
84 Options
85 -------
86 -h, --help Print this help information
88 --env Use shell ENVIRONMENT variables to fill the
89 $placeholders in the template.
91 --pickle <file> Use a variables from a dictionary stored in Python
92 pickle file to fill $placeholders in the template.
93 If <file> is - stdin is used:
94 '%(scriptName)s --pickle -'
96 Description
97 -----------
99 This interface allows you to execute a Cheetah template from the command line
100 and collect the output. It can prepend the shell ENVIRONMENT or a pickled
101 Python dictionary to the template's $placeholder searchList, overriding the
102 defaults for the $placeholders.
104 """ % {'scriptName':self._scriptName,
105 'Version':Version,
108 # vim: shiftwidth=4 tabstop=4 expandtab