A simple Python templating tool
The other day I wrote a very simple Python utility, that some might find
useful (the code is on GitHub). It’s a
command line program called new.py
, which allows you to create new files
or directories from templates. So, for instance, I often have common
boilerplate code when writing a Python script, similar to this:
#!/usr/bin/env python
"""
Author: Gertjan van den Burg
Date:
License: GPL v3
"""
def main():
pass
if __name__ == '__main__':
main()
Now, I store this in the new.py
template directory (by default this is
~/.newpy_templates
) as the file python.py
. Then, if I run new.py
on the command line without any arguments, I get:
Usage: ./new.py target [output_name]
Available targets:
Name File / Dir
---- ----------
python -> python.py
It’s then easy to create a file from a template, simply by running:
$ new.py python myfile.py
will generate a file named myfile.py
with the contents of the python.py
file
in the template directory. Personally, I use this not only for python files, but
also for LaTeX document templates and Beamer slides. The latter two examples are
actually directories, which new.py
also supports.
Finally, I have the following alias in my ~/.bashrc
file:
alias new='/path/to/new.py'
which makes new.py
even easier and more intuitive to use:
$ new python myfile.py
You can find new.py
on GitHub.