-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmantidpythonfromtemplate
executable file
·90 lines (71 loc) · 2.73 KB
/
mantidpythonfromtemplate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python3
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import sys
__version__ = "0.0.2"
try:
import yaml
HAVE_YAML = True
except ImportError:
HAVE_YAML = False
def readTemplate(filename):
with open(filename, 'r') as handle:
template = handle.read()
return template
def readConfig(filename, parser):
config = {} # default is empty dict
if HAVE_YAML and filename:
if not os.path.exists(filename):
parser.error("Config file does not exist")
print("Reading configuration from '%s'" % filename)
with open(filename, 'r') as handle:
config = yaml.load(handle)
return config
def getKeywords(template):
import re
return re.findall(r'%\((.+)\)', template)
def missingKeywords(template, argDict):
missing = []
for keyword in getKeywords(template):
if not keyword in argDict.keys():
missing.append(keyword)
return missing
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Fill in a template using pythons engine')
parser.add_argument('infile', metavar="INFILE",
help="Template file to read in")
if HAVE_YAML:
parser.add_argument('-c', '--config',
help="specify yaml file with key/value information to fill in template")
parser.add_argument('-o', '--outfile',
help="File to write out. Defaults to abbreviated template name in the current directory")
parser.add_argument('argvec', nargs='*', metavar="ARG",
help="Key/value pairs to fill into the template")
args = parser.parse_args()
if not HAVE_YAML:
print("Install PyYAML for extra options")
args.config = None
if not os.path.exists(args.infile):
parser.error("Input file does not exist")
# output file
if args.outfile is None:
args.outfile = os.path.split(args.infile)[-1].replace('.template', '')
print("Reading '%s'" % args.infile)
# read in the template
scriptText = readTemplate(args.infile)
argList = sys.argv[2:]
argDict = readConfig(args.config, parser)
for i in range(0, len(argList), 2):
argDict[argList[i]] = argList[i+1]
print("Generating '%s'" % args.outfile)
try:
scriptText = scriptText % argDict
except KeyError as e:
print("Failed to supply value for key %s" % str(e))
missing = missingKeywords(scriptText, argDict)
missing = ["'%s'" % item for item in missing]
print("Full list of missing keywords: %s" % ', '.join(missing))
with open(args.outfile, 'w') as handle:
handle.write(scriptText)