Cog

Cog is a file generation tool. It lets you use pieces of Python code as generators in your source files to generate whatever text you need.

This page describes version 3.4.1, released March 7, 2024.

What does it do?

Cog transforms files in a very simple way: it finds chunks of Python code embedded in them, executes the Python code, and inserts its output back into the original file. The file can contain whatever text you like around the Python code. It will usually be source code.

For example, if you run this file through cog:

// This is my C++ file.
...
/*[[[cog
import cog
fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
for fn in fnames:
    cog.outl("void %s();" % fn)
]]]*/
//[[[end]]]
...

it will come out like this:

// This is my C++ file.
...
/*[[[cog
import cog
fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
for fn in fnames:
    cog.outl("void %s();" % fn)
]]]*/
void DoSomething();
void DoAnotherThing();
void DoLastThing();
//[[[end]]]
...

Lines with triple square brackets are marker lines. The lines between [[[cog and ]]] are the generator Python code. The lines between ]]] and [[[end]]] are the output from the generator.

Output is written with cog.outl(), or if you use the -P option, normal print() calls.

When cog runs, it discards the last generated Python output, executes the generator Python code, and writes its generated output into the file. All text lines outside of the special markers are passed through unchanged.

The cog marker lines can contain any text in addition to the triple square bracket tokens. This makes it possible to hide the generator Python code from the source file. In the sample above, the entire chunk of Python code is a C++ comment, so the Python code can be left in place while the file is treated as C++ code.

Installation

Cog requires Python 3.7 or higher.

Cog is installed in the usual way, except the installation name is “cogapp”, not “cog”:

$ python3 -m pip install cogapp

You should now have a “cog” command you can run.

See the changelog for the history of changes.

Cog is distributed under the MIT license. Use it to spread goodness through the world.

More