Last active
December 3, 2015 08:46
-
-
Save kokumura/f0868498972900bd54be to your computer and use it in GitHub Desktop.
Command line Jinja2 renderer
This file contains 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 | |
# -*- coding:utf8 -*- | |
import sys, optparse | |
import jinja2 | |
def main(args, params): | |
encoding = params.encoding | |
tpl = jinja2.Template(sys.stdin.read().decode(encoding)) | |
param = dict() | |
ex_args = list() | |
for item in args: | |
item = unicode(item, encoding) | |
if '=' in item: | |
k,v = item.split('=',1) | |
param[k] = v | |
else: | |
ex_args.append(item) | |
param['args'] = ex_args | |
sys.stdout.write(tpl.render(param).encode(encoding)) | |
if __name__ == '__main__': | |
usage = """\ | |
usage: %prog [-e encoding] [var1=value1 var2=value2 ...] [arg0 arg1 ...] | |
render jinja2 template string using given parameter. | |
example: | |
$ echo "{{hello}} {{world}} {{args[0]}} !" | jj hello="Hello" world="World" "Foo" | |
Hello World Foo ! | |
""" | |
parser = optparse.OptionParser(usage=usage) | |
parser.add_option("-e", "--encoding",action="store", default="utf-8",help="character encoding (utf-8 default)") | |
options, args = parser.parse_args() | |
main(args, options) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment