背景:我正在使用生成报告。
import genshi
import os
from genshi.template import MarkupTemplate
files = [
r"a\b\c.txt",
r"d/e/f.txt",
]
html = '''
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/">
<head>
</head>
<body>
<p py:for="f in sorted(files, key=lambda x: x.lower().split(os.path.sep))">
${f}
</p>
</body>
</html>
'''
template = MarkupTemplate(html)
stream = template.generate(
files = files
)
print(stream.render('html'))问题: Genshi抛出一个UndefinedError异常,因为它不知道我导入的模块。
D:\SVN\OSI_SVT\0.0.0.0_swr65430\srcPy\OSI_SVT>python36 test.py
Traceback (most recent call last):
File "test.py", line 26, in <module>
print(stream.render('html'))
File "C:\Python36\lib\site-packages\genshi\core.py", line 184, in render
return encode(generator, method=method, encoding=encoding, out=out)
...
genshi.template.eval.UndefinedError: "os" not defined问题:是否有办法使Genshi自动了解导入的模块?
如果在Genshi中本机无法实现这一点,我将接受一个以编程方式创建一个模块集合的答案,这样就可以将它们传递给generate()调用。例如:generate(**args)
我尝试过的:
os = os添加到template.generate()调用中。这是可行的,但它是恼人和容易出错,不得不重复我的进口。发布于 2018-11-05 20:38:17
我在Genshi外面找到了一种方法。这种方法将所有全局和本地对象(导入以及全局和局部变量)添加到字典中。然后将字典作为关键字args传递给generate() (如果您对此不熟悉,请参见这个答案 )。
import genshi
import os
import types
from genshi.template import MarkupTemplate
html = '''
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/">
<head>
</head>
<body>
<p py:for="f in sorted(files, key=lambda x: x.lower().split(os.path.sep))">
${f}
</p>
</body>
</html>
'''
def main():
files = [
r"a\b\c.txt",
r"d/e/f.txt",
]
generation_args = {}
for scope in [globals(), locals()]:
for name, value in scope.items():
generation_args[name] = value
template = MarkupTemplate(html)
stream = template.generate(**generation_args)
print(stream.render('html'))
main()https://stackoverflow.com/questions/53157951
复制相似问题