Files generation in Python

Français   |   Source

It is fairly easy to generate text (therefore ASCII files, therefore source code) in Python using templates. I often see misuse of print to do so, whereas it seems much more elegant to use templates.

Basic principle

The basic principle is very simple: you will create a source file with variables to substitute (using the usual Python formatting); this file will be loaded, then substitutions will be made and a modified file will be written.

Before going into technicalities, it is worth emphasizing that this way is much more pleasant and much less error-prone that a long list of print. Pleasant, because it is easy (and much less combersome) to start from a preexisting file; on top of it, keeping the file extension, we'll keep the text formatting in our favorite text editor. Less error-prone, for exactly the same reason: working from an existing file means that we can check that everything is working beforehand; we therefore avoid complicated debugging where Python bugs are intricated with bugs in the sources.

Example

We can use it on a simple bash hello world:

  • we start with a file containgin the var variable:
$ more ex.sh
#!/bin/bash
echo "%(var)s"
  • and we then open, substitute and write a new file in Python:
#!/usr/bin/env python

template = open("ex.sh", "rt").read()
data = {"var": "Hello world!"}
with open("exm.sh", "wt") as output:
    output.write(template %data)
  • ... that we can launch:
$ sh exm.sh
Hello world!

A more complex example can be found on GitHub, but it is basically the same. I also used this in DUMSES-Hybrid for example (this example is actually interesting for tabs because I needed real tabs, not spaces, to generate makefiles).