Created
February 19, 2015 20:41
-
-
Save kennedyj/ae0d3d2ac599607de454 to your computer and use it in GitHub Desktop.
Stupid Simple Jinja2 CLI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse | |
import jinja2 | |
import json | |
import sys | |
""" | |
read a template from stdin or a file, load variables from json or as an | |
argument, and then output to file or stdout | |
""" | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-c', '--config', default=None, help='load vars from file') | |
parser.add_argument('-v', '--vars', default=None, help='vars from input') | |
parser.add_argument('-i', '--input', default=None, help='source file') | |
parser.add_argument('-o', '--output', default=None, help='output file') | |
parser.add_argument('-a', '--append', default=False, action='store_true', | |
help='append to out') | |
(args, extra) = parser.parse_known_args() | |
source, data = None, None | |
if args.input: | |
with open(args.input, 'r') as f: | |
source = f.read() | |
else: | |
source = sys.stdin.read() | |
if args.config: | |
with open(args.config, 'r') as f: | |
data = json.load(f) | |
elif args.vars: | |
data = json.loads(args.vars) | |
else: | |
data = {} | |
jenv = jinja2.Environment(trim_blocks=True) | |
result = jenv.from_string(source).render(**data) | |
if args.output: | |
open_method = 'w' | |
if args.append: | |
open_method = 'a' | |
with open(args.output, open_method) as f: | |
f.write(result) | |
else: | |
print result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment