基于输入和输出模板转换文本文件
templatio的Python项目详细描述
关于templatio
templatio是一个python 3实用程序,它使用TextFSM和Jinja2来 根据输入和输出模板转换文本文件。
它可以被开发人员用作模块,也可以被用户用作脚本。
它支持输入模板和 Jinja2 syntax用于输出模板。
templatio是自由软件,在Apache License, Version 2.0下发布。
Templatio是由Marco Bellaccini(Marco.Bellaccini,at!)写的。在一顿丰盛的午餐后。
快速启动
假设我们要转换一个简单的格式化文本文件 一个好的html文件。
这是输入文本文件。
infile.txt:
Name: John Surname: Doe Country: Atlantis
首先,我们需要使用TextFSM syntax创建一个输入模板。
intempl.txt:
Value Name (\S+) Value Surname (\S+) Value Country (\S+) Start ^Name: ${Name} ^Surname: ${Surname} ^Country: ${Country}
然后,我们需要使用Jinja2 syntax编写输出模板。
outtemp.html:
<!DOCTYPE html><html><head><title>Hello</title></head><body><p>Hi, I'm {{ Name }} {{ Surname }} and I come from {{ Country }}.</p></body></html>
现在,我们可以通过将templatio作为脚本运行来转换文件:
templatio intempl.txt outtempl.html infile.txt outfile.html
这就是我们得到的。
outfile.html:
<!DOCTYPE html><html><head><title>Hello</title></head><body><p>Hi, I'm John Doe and I come from Atlantis.</p></body></html>
也可以将templatio用作python模块:
importtemplatioinData="""Name: John Surname: Doe Country: Atlantis"""inTemplate="""Value Name (\S+) Value Surname (\S+) Value Country (\S+) Start ^Name: ${Name} ^Surname: ${Surname} ^Country: ${Country}"""outTemplate="""<!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <p>Hi, I'm {{ Name }} {{ Surname }} and I come from {{ Country }}.</p> </body> </html>"""outData=templatio.parseInToOut(inTemplate,outTemplate,inData)
让我们了解更多
下面是一个稍微复杂一点的例子,它让您了解 可以利用TextFSM和Jinja2模板 执行高级转换。
假设我们希望从 有两个驱动器的系统上的df命令。
与驱动器关联的json对象应该有一个alarm值集 如果磁盘使用率超过80%,则返回true。
这是输入和模板文件。
infile.txt:
Filesystem 1K-blocks Used Available Use% Mounted on udev 2014208020142080% /dev tmpfs 40510058483992522% /run /dev/sda1 1644735648930161069914832% / /dev/sda2 101732489301693442396% /mnt/foo tmpfs 2025484222424180306011% /dev/shm tmpfs 5120451161% /run/lock tmpfs 2025484020254840% /sys/fs/cgroup tmpfs 405096564050401% /run/user/1000
intempl.txt:
Value Drive1 (\S+) Value Drive1Usage (\d+) Value Drive2 (\S+) Value Drive2Usage (\d+)# start state Start # after parsing drive1 data, switch to Drive1parsed state ^/dev/${Drive1} .* ${Drive1Usage}% -> Drive1parsed # drive 1 parsed state Drive1parsed ^/dev/${Drive2} .* ${Drive2Usage}%
outtemp.json:
{% macro checkusage(usage) -%}{% if usage > 80 -%}true{% else %}false{% endif %}{%- endmacro -%}{"drives": {"drive1": {"name": "{{ Drive1 }}", "usage": "{{ Drive1Usage }}", "alarm": {{ checkusage(Drive1Usage | int)}}}, "drive2": {"name": "{{ Drive2 }}", "usage": "{{ Drive2Usage }}", "alarm": {{ checkusage(Drive2Usage | int)}}}}}
我们运行templatio(在本例中,我们将其用作脚本):
templatio intempl.txt outtempl.json infile.txt report.json
我们得到了很好的结果。
report.json:
{"drives":{"drive1":{"name":"sda1","usage":"32","alarm":false},"drive2":{"name":"sda2","usage":"96","alarm":true}}}