本文整理汇总了Python中jinja2.Template.encode方法的典型用法代码示例。如果您正苦于以下问题:Python Template.encode方法的具体用法?Python Template.encode怎么用?Python Template.encode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jinja2.Template
的用法示例。
在下文中一共展示了Template.encode方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check_cpp
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
def check_cpp(argv, prog):
CMD_TPL1='for d in {{dirs}};do find $d -name "*.cc" -o -name "*.cpp" -o -name "*.h" -o -name "*.hpp" -o -name "*.c" | xargs -I {} cpplint {}; done'
CMD_TPL2='for d in {{dirs}};do find $d -name "*.cc" -o -name "*.cpp" -o -name "*.h" -o -name "*.hpp" -o -name "*.c" | xargs -I {} cpplint {} >> {{out}}/cpplint.txt 2>&1;done'
argparser = argparse.ArgumentParser(description="octopus ", prog=prog)
argparser.add_argument('-o', dest='output_dir',
help='文件输出目录', default='')
argparser.add_argument(
'dirs', metavar='N', nargs='*',
help='要检查的目录')
args = argparser.parse_args(argv)
if args.output_dir:
local('[ -d {out} ] || mkdir -p {out}'.format(out=args.output_dir))
local('if [ -f {out}/cpplint.txt ];then rm -f {out}/cpplint.txt; fi'.format(
out=args.output_dir))
cmd = Template(CMD_TPL2.decode('utf-8'));
cmd = cmd.render(out=args.output_dir, dirs=' '.join(args.dirs))
cmd = cmd.encode('utf-8')
pyshell.shell(cmd, warn_only=True)
converter = CpplintConverter()
converter.parse(args.output_dir+'/cpplint.txt')
converter.write(args.output_dir+'/cpplint.xml')
else:
cmd = Template(CMD_TPL1.decode('utf-8'));
cmd = cmd.render(out=args.output_dir, dirs=' '.join(args.dirs))
cmd = cmd.encode('utf-8')
pyshell.shell(cmd, warn_only=True)
示例2: render_results
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
def render_results(results, approved):
from jinja2 import Template
items = results.values()
items.sort(key=lambda x: x.name.lower())
rv = Template(RESULT_TEMPATE, autoescape=True).render(results=items,
approved=approved)
fd, filename = tempfile.mkstemp(suffix='.html')
os.fdopen(fd, 'w').write(rv.encode('utf-8') + '\n')
return filename
示例3: _replace_template
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
def _replace_template(file_path, variables):
if os.path.exists(file_path):
with open(file_path, 'r') as f:
from jinja2 import Template
rendered = Template(f.read().decode('utf-8')).render(**variables)
f = open(file_path, 'w')
f.write(rendered.encode('utf-8'))
f.close()
示例4: main
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
def main():
with open("input.txt") as fab_f:
with open("out.jinja") as jinja_f:
with open('out.html', 'w') as out_f:
source = highlight(fab_f.read(),
FabLexer(),
HtmlFormatter(style="friendly"))
out = Template(jinja_f.read()).render(source=source)
out_f.write(out.encode('utf-8'))
示例5: run_script_with_context
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
def run_script_with_context(script_path, cwd, context):
"""
Executes a script after rendering with it Jinja.
:param script_path: Absolute path to the script to run.
:param cwd: The directory to run the script from.
:param context: Cookiecutter project template context.
"""
_, extension = os.path.splitext(script_path)
contents = io.open(script_path, "r", encoding="utf-8").read()
with tempfile.NamedTemporaryFile(delete=False, mode="wb", suffix=extension) as temp:
output = Template(contents).render(**context)
temp.write(output.encode("utf-8"))
run_script(temp.name, cwd)
示例6: gen_conf
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
def gen_conf(argv, prog):
argparser = argparse.ArgumentParser(description="octopus ", prog=prog)
argparser.add_argument('-t', '--tpl', dest='tpl',
help='输入的模版文件', required=True)
argparser.add_argument('-o', '--output', dest='output',
help='输出文件路径', required=True)
argparser.add_argument(
'params', metavar='N', nargs='*',
help='模版参数')
args = argparser.parse_args(argv)
if not os.path.exists(args.tpl):
print args.tpl + ' not exist'
sys.exit(1)
s = open(args.tpl, 'r').read()
params = {}
for p in args.params:
(k,v) = p.split('=')
params[k] = v
out = Template(s.decode('utf-8')).render(params)
open(args.output, 'w').write(out.encode('utf-8'))
示例7: produce
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
def produce():
info = json.load(open(PREFIX + MANIFEST, 'rb'))
for file_name in info["spine"]:
data = open(PREFIX + file_name + '.html', 'rb').read()
doc = html.document_fromstring(data.decode('utf-8'))
body = doc.find('.//body')
body.tag = 'div'
title = doc.find('.//h1')
title = title.text.strip() if title is not None else ''
print [title]
rename_tag(doc, 'h4', 'h5')
rename_tag(doc, 'h3', 'h4')
rename_tag(doc, 'h2', 'h3')
rename_tag(doc, 'h1', 'h2')
tpl = {
"title": title,
"body": html.tostring(body),
"toc": info.get("TOC")
}
content = Template(TEMPLATE).render(tpl)
fh = open(file_name + '.html', 'wb')
fh.write(content.encode('utf-8'))
fh.close()
示例8: if
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
#!/usr/bin/env python2.7
import json, os
from jinja2 import Template
for lang in ['en', 'de', 'es', 'el', 'fr']:
directory = '.' if (lang=='en') else lang
if not os.path.exists(directory):
os.makedirs(directory)
with open('%s/index.html' % directory, 'w') as out:
with open('template.html') as t:
with open('%s.json' % lang) as f:
output = Template(t.read().decode('utf8')).render(**json.load(f, encoding='utf-8'))
out.write(output.encode('utf-8'))
示例9: Ansi2HTMLConverter
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
import json
from jinja2 import Template
from ansi2html import Ansi2HTMLConverter
from ansi2html.style import get_styles
conv = Ansi2HTMLConverter()
def shell_to_html(shell):
return conv.convert(shell, False)
if __name__ == '__main__':
result = Template(open("template.html", "r").read()).render(data=json.load(open("./logs.json")), convert=shell_to_html, shell_css="\n".join(map(str, get_styles(conv.dark_bg, conv.scheme))))
open("index.html", "w").write(result.encode("Utf-8"))
示例10: open
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
import sys
import json
from jinja2 import Template
sys.path.append('./libs')
from pynliner_encoded import Pynliner
folder = sys.argv[1]
if folder != '':
template = open(folder + '/template.html', 'r').read()
css = open(folder + '/style.css', 'r').read()
with open(folder + '/data.json') as data_file:
data = json.load(data_file)
template = Template(template.decode('utf-8'))
template = template.render(data)
p = Pynliner()
p.from_string(template).with_cssString(css)
template = p.run()
open(folder + '/index.html', 'w').write(template.encode('utf-8'))
print "Generating of %s template is complete" % folder
print "Please look through %s/index.html file" % folder
else:
print "You need to specify a template name as a parameter"
示例11: cookiepatch
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
def cookiepatch():
parser = argparse.ArgumentParser(description='Tool to apply / create patch from '
'cookiecutter templates')
parser.add_argument('--template', type=str,
help='an integer for the accumulator')
parser.add_argument('--diff', type=str, nargs='+',
help='versions passed for git diff')
parser.add_argument('--show', action='store_true',
help='Just print diff')
args = parser.parse_args()
conf_file = None
if os.path.exists(CONF_PATH):
with open(CONF_PATH) as f:
conf_file = json.load(f)
if args.template:
template = args.template
elif conf_file and 'template' in conf_file:
template = conf_file['template']
else:
template = input('Input template repository url: ')
if args.diff:
diff = args.diff
elif conf_file and 'revision' in conf_file:
diff = [conf_file['revision']]
else:
cur = input('Input template version applied currently: ')
to = input('Input version to follow [master]: ') or 'master'
diff = [cur, to]
no_input = False
config_dict = get_user_config(config_file=USER_CONFIG_PATH)
parsed_template = expand_abbreviations(template, config_dict)
repo_dir = clone(repo_url=parsed_template,
clone_to_dir=config_dict['cookiecutters_dir'],
checkout=None, no_input=no_input)
patch_bytes = subprocess.check_output(['git', 'diff'] +
diff +
['--', '{{cookiecutter.repo_name}}'],
cwd=repo_dir)
patch_str = patch_bytes.decode()
context_file = os.path.join(repo_dir, 'cookiecutter.json')
context = generate_context(
context_file=context_file,
default_context=config_dict['default_context'],
extra_context={},
)
if conf_file:
context['cookiecutter'] = conf_file['variables']
else:
# prompt the user to manually configure at the command line.
# except when 'no-input' flag is set
context['cookiecutter'] = prompt_for_config(context, no_input)
rendered = Template(patch_str).render(**context)
if args.show:
print(rendered)
return
p = subprocess.Popen(['patch', '-Np1', '--no-backup-if-mismatch'], stdin=subprocess.PIPE,
cwd='..')
p.communicate(rendered.encode())
# Generate cookiepatcher JSON
if len(diff) == 1:
rev = 'HEAD'
else:
rev = diff[-1]
revision_bytes = subprocess.check_output(['git', 'rev-parse'] + [rev],
cwd=repo_dir)
revision_str = revision_bytes.decode().rstrip('\n')
json_content = {
'revision': revision_str,
'variables': context['cookiecutter'],
'template': template
}
with open(CONF_PATH, 'w') as f:
json.dump(json_content, f, ensure_ascii=False, indent=2, sort_keys=True)
示例12: make_package
# 需要导入模块: from jinja2 import Template [as 别名]
# 或者: from jinja2.Template import encode [as 别名]
def make_package(self, instance, program_info, program_path, deploy_env,
default_runpath, remote_program_path):
"""将文件打包,方便拷贝. """
# TODO :打包的时候排除掉.svn文件.
package = program_info.package
print 'make_package instance=%s' % (instance)
if instance['package']:
package = program_info.packages[instance['package']]
print 'make_package package=%s' % (package)
for ext in package.extends:
ext_package = program_info.packages[ext]
package.dirs.extend(ext_package.dirs)
package.files.extend(ext_package.files)
package.tpls.extend(ext_package.tpls)
current_dir = os.getcwd()
pkg_file = '%s.tar.gz' % (instance['name'])
pkg_file_full_path = current_dir + '/' + pkg_file
os.chdir(program_path)
local('[ ! -d __instance ] || rm -rf __instance')
local('mkdir __instance')
local(' if [ -d METAINFO ] ;then cp -r METAINFO __instance/;fi')
common_args = instance['args']
common_args['env'] = deploy_env
common_args['name'] = instance['name']
if not 'run_path' in common_args:
common_args['run_path'] = default_runpath
for d in package.dirs:
src = Template(d.src.decode('utf-8')).render(common_args).encode('utf-8')
local('cp -r %s __instance/%s' % (src, d.to))
for d in package.files:
src = Template(d.src.decode('utf-8')).render(common_args).encode('utf-8')
to_dir = '__instance/' + os.path.dirname(d.to)
if not os.path.isdir(to_dir):
print 'mkdir ' , to_dir
os.makedirs(to_dir)
local('cp %s __instance/%s' % (src, d.to))
print 'start prepare template'
for d in package.tpls:
src = Template(d.src.decode('utf-8')).render(common_args).encode('utf-8')
s = open(src, 'r').read()
#params = {}
#for k in d.params:
# params[k] = common_args[k]
out = Template(s.decode('utf-8')).render(common_args)
target_file = '__instance/'+d.to
to_dir = os.path.dirname(target_file)
if not os.path.isdir(to_dir):
os.makedirs(to_dir)
local('cp %s %s' % (src, target_file))
open(target_file, 'w').write(out.encode('utf-8'))
role_str = ','.join(instance['roles'])
local('[ -d __instance/METAINFO ] || mkdir __instance/METAINFO')
local('echo roles:%s >> __instance/METAINFO/deploy.inf' % (role_str))
os.chdir('__instance')
self.create_start_scripts(instance['name'], instance['roles'],
program_info.get_scripts(), remote_program_path,
default_runpath, common_args)
os.chdir(program_path)
local('echo `pwd` && cd __instance && tar -zcf %s *' % ( pkg_file_full_path))
local('rm -rf __instance')
os.chdir(current_dir)
return pkg_file_full_path