Created
May 6, 2015 21:17
-
-
Save junmakii/74a5789ac84a3549fecf to your computer and use it in GitHub Desktop.
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/python | |
| #-*- coding: utf-8 -*- | |
| import os, sys | |
| import argparse | |
| import jinja2 | |
| import json | |
| def parse_args(argv): | |
| parser = argparse.ArgumentParser(description='') | |
| parser.add_argument('-o', '--output', action='store') | |
| parser.add_argument('-j', '--json', nargs='+', default=[], action='store') | |
| parser.add_argument('template', action='store') | |
| args = parser.parse_args(argv) | |
| return args | |
| def main(argv): | |
| args = parse_args(argv) | |
| template_path = args.template | |
| if os.path.isdir(args.output): | |
| output = os.path.join(args.output, os.path.basename(template_path)) | |
| elif args.output: | |
| output = args.output | |
| else: | |
| output = os.path.basename(template_path) | |
| with open(template_path, 'r') as fp: | |
| template_str = fp.read() | |
| template = jinja2.Template(template_str) | |
| template_context = {} | |
| for json_path in args.json: | |
| with open(json_path) as fp: | |
| json_str = fp.read() | |
| json_data = json.loads(json_str) | |
| template_context.update(json_data) | |
| template_result = template.render(template_context) | |
| template_result_utf8 = template_result.encode('utf8') | |
| with open(output, 'w') as fp: | |
| fp.write(template_result_utf8) | |
| if args.output is None: | |
| print(template_result) | |
| if __name__ == '__main__': | |
| main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment