Skip to content

Instantly share code, notes, and snippets.

@GaryLee
Created July 23, 2024 08:05
Show Gist options
  • Save GaryLee/e042992e841a073fd1e6c754ea0fa3d7 to your computer and use it in GitHub Desktop.
Save GaryLee/e042992e841a073fd1e6c754ea0fa3d7 to your computer and use it in GitHub Desktop.
Generate document with TOML and MAKO template.
#!python3
# coding: utf-8
import sys
from os import path
import tomli as toml
from mako.template import Template
def main():
if len(sys.argv) != 3:
sys.exit('Usage: toml2tmpl.py <toml file> <mako template file>')
if not sys.argv[1].endswith('.toml') or not path.isfile(sys.argv[1]):
sys.exit('ERROR: The first argument must be a valid file with .toml extension')
if not sys.argv[2].endswith('.mako') or not path.isfile(sys.argv[2]):
sys.exit('ERROR: The second argument must be a valid file with .mako extension')
data = toml.load(open(sys.argv[1], 'rb'))
tmpl = template(filename=sys.argv[2], output_encoding='utf-8', encoding_errors='replace')
content = template.render(data=data)
output_filename = path.splitext(sys.argv[2])[0]
open(output_filename, 'wb').write(content)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment