python模板使用方法学习,jinja

通过python调用jinja文件,生成模板方法。
在此做个记录,随时回头查看。

python文件

import os
from jinja2 import Environment, FileSystemLoader

template_file = "template.jinja"
output_file = "template.c"
script_file  = os.path.realpath(__file__)
script_path  = os.path.dirname(script_file)

src_file_path = os.path.join(script_path, "file")
src_files = os.listdir(src_file_path)

src_fnames = []
for file in src_files:
    fname,fename = os.path.splitext(file)
    if fename == '.py':
        src_fnames.append(fname)
print(src_fnames)

env = Environment(loader=FileSystemLoader(script_path))
template = env.get_template(template_file)
with open(output_file, 'w') as fd:
    fd.write(template.render(src_fnames=src_fnames))

print("done!")

jinja文件

#include <stdio.h>

int main()
{
    
    
	printf("In file dir has *.py files:\n");
{
    
    % for src_fname in src_fnames %}
	printf("file:%s.py\n", "{
    
    {src_fname}}");
{
    
    %- endfor %}

	return 0;
}

源代码链接:https://download.csdn.net/download/niu_88/15791332

猜你喜欢

转载自blog.csdn.net/niu_88/article/details/114807378