因此,基本上,我正在运行一个生成一些文件的python脚本。问题是:生成每个.cpp和.hpp文件都没有问题,而脚本引发了一个异常,生成了一个异常的CMakeLists.txt:
Traceback (most recent call last):
File "enum_generator.py", line 115, in <module>
generate_cmakelists(result)
File "enum_generator.py", line 98, in generate_cmakelists
'templates/cmakelists_enums_template.jinja2', result=result)
File "enum_generator.py", line 43, in render_to_file
jinja_template = Template(template_file)
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 945, in __new__
return env.from_string(source, template_class=cls)
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 880, in from_string
return cls.from_code(self, self.compile(source), globals, None)
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 591, in compile
self.handle_exception(exc_info, source_hint=source_hint)
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "<unknown>", line 8, in template
jinja2.exceptions.TemplateSyntaxError: unexpected '%'
我尝试了相同的代码,带有用于.cpp和.hpp文件的模板,并且工作正常。接下来,您将看到CMake_template和python脚本
cmake_minimum_required(VERSION 3.0.0)
project(ART_Plugin_Enums)
set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR})
add_library(ART_Plugin_Enums ${LIBRARY_TYPE}
{% for category in result.keys() -%}
enums/{{category}}Enum.hpp
inc/{{category}}EnumPlugin.hpp
inc/{{category}}EnumPlugin_module.hpp
src/{{category}}EnumPlugin.cpp
src/{{category}}numPlugin_module.cpp
{%endfor%})
这是脚本:
def render_to_file(target_file_path, template_name, *args, **kwargs):
with open(target_file_path, 'w+') as f:
template_file = open(os.path.join(SCRIPT_LOCATION,
template_name)).read()
jinja_template = Template(template_file)
print("-- Generating {}".format(target_file_path))
f.write(jinja_template.render(*args, **kwargs))
def generate_cmakelists(result):
target_file_path = os.path.join(SCRIPT_LOCATION, '..', "CmakeLists.txt")
return render_to_file(
target_file_path,
'templates/cmakelists_enums_template.jinja2', result=result)
generate_cmakelists(result)
我很困惑,因为我不明白为什么Jinja无法识别for中的%。有任何线索吗?
答案 0 :(得分:-1)
实际上,我认为我打开的文件太多,并且搞乱了与正在渲染的文件的编辑。很抱歉,您会浪费时间,代码实际上可以正常工作。