Debian Codegraph @

Cheetah/TemplateCmdLineIface.py

raw symbols SCIP
1
2 import sys
3 import os
4 import getopt
5 import os.path
6 try:
7 from cPickle import load
8 except ImportError:
9 from pickle import load
10 from json import load as jsonload
11
12 from .Version import Version
13
14
15 class Error(Exception):
16 pass
17
18
19 class CmdLineIface:
20 """A command line interface to compiled Cheetah template modules."""
21
22 def __init__(self, templateObj,
23 scriptName=os.path.basename(sys.argv[0]),
24 cmdLineArgs=sys.argv[1:]):
25
26 self._template = templateObj
27 self._scriptName = scriptName
28 self._cmdLineArgs = cmdLineArgs
29
30 def run(self):
31 """The main program controller."""
32
33 self._processCmdLineArgs()
34 print(self._template)
35
36 def _processCmdLineArgs(self):
37 try:
38 self._opts, self._args = getopt.getopt(
39 self._cmdLineArgs, 'h', ['help', 'env', 'pickle=', 'json=']
40 )
41
42 except getopt.GetoptError as v:
43 # print help information and exit:
44 print(v)
45 print(self.usage())
46 sys.exit(2)
47
48 for o, a in self._opts:
49 if o in ('-h', '--help'):
50 print(self.usage())
51 sys.exit()
52 if o == '--env':
53 self._template.searchList().insert(0, os.environ)
54 if o == '--pickle':
55 if a == '-':
56 if hasattr(sys.stdin, 'buffer'):
57 stdin = sys.stdin.buffer # Read binary data from stdin
58 else:
59 stdin = sys.stdin
60 unpickled = load(stdin)
61 self._template.searchList().insert(0, unpickled)
62 else:
63 f = open(a, 'rb')
64 unpickled = load(f)
65 f.close()
66 self._template.searchList().insert(0, unpickled)
67 if o == '--json':
68 if a == '-':
69 if hasattr(sys.stdin, 'buffer'):
70 stdin = sys.stdin.buffer # Read binary data from stdin
71 else:
72 stdin = sys.stdin
73 unjsoned = jsonload(stdin)
74 self._template.searchList().insert(0, unjsoned)
75 else:
76 f = open(a, 'r')
77 unjsoned = jsonload(f)
78 f.close()
79 self._template.searchList().insert(0, unjsoned)
80
81 def usage(self):
82 return """Cheetah %(Version)s template module command-line interface
83
84 Usage
85 -----
86 %(scriptName)s [OPTION]
87
88 Options
89 -------
90 -h, --help Print this help information
91
92 --env Use shell ENVIRONMENT variables to fill the
93 $placeholders in the template.
94
95 --pickle <file> Use a variables from a dictionary stored in Python
96 pickle file to fill $placeholders in the template.
97 If <file> is - stdin is used:
98 '%(scriptName)s --pickle -'
99
100 Description
101 -----------
102
103 This interface allows you to execute a Cheetah template from the command line
104 and collect the output. It can prepend the shell ENVIRONMENT or a pickled
105 Python dictionary to the template's $placeholder searchList, overriding the
106 defaults for the $placeholders.
107
108 """ % {'scriptName': self._scriptName, 'Version': Version}
109
110 # vim: shiftwidth=4 tabstop=4 expandtab