Last active
June 23, 2017 10:37
-
-
Save GaryLee/f6d86ff4cfe33559c41bc4f19248dec2 to your computer and use it in GitHub Desktop.
Generate content according to INI and template.
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
| #!python | |
| # coding: utf-8 | |
| """Generate content according to INI and template.""" | |
| import sys | |
| import os | |
| import codecs | |
| from argparse import ArgumentParser | |
| from ConfigParser import ConfigParser | |
| from collections import OrderedDict | |
| from mako.template import Template | |
| class Ini2Tmpl(object): | |
| """Generate context according to given INI file and template file.""" | |
| def __init__(self, ini=None, tmpl=None): | |
| """Parser test.""" | |
| self.ini = ini | |
| self.tmpl = tmpl | |
| def make(self, out=sys.stdout): | |
| """Make content from INI and template.""" | |
| ctx = ConfigParser(dict_type=OrderedDict) | |
| ctx.optionxform = str # Allow different case used in option name. | |
| ctx.readfp(codecs.open(self.ini, 'r', 'utf8')) | |
| env = os.environ | |
| env['ini'] = self.ini | |
| env['tmpl'] = self.tmpl | |
| env['out'] = out | |
| if isinstance(out, (str, unicode)): | |
| with open(out, 'w') as fd: | |
| fd.write(Template(filename=self.tmpl).render_unicode(ctx=ctx, env=env)) | |
| else: | |
| out.write(Template(filename=self.tmpl).render_unicode(ctx=ctx, env=env)) | |
| def main(): | |
| """Main entry.""" | |
| parser = ArgumentParser(description='Generate content according to INI and template.') | |
| parser.add_argument('-i', '--ini', dest='ini', help='INI file.') | |
| parser.add_argument('-t', '--tmpl', dest='tmpl', help='Template file.') | |
| parser.add_argument('-o', '--out', dest='out', help='Output file.') | |
| args = parser.parse_args() | |
| Ini2Tmpl(ini=args.ini, tmpl=args.tmpl).make(out=args.out) | |
| if __name__ == '__main__': | |
| sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment