Cog: Evaluate Arbitrary Python Fragments in a Template Document

You provide any text document with embedded fragments of Python, and Cog renders it:

using namespace std;

#include <iostream>

int main() {
    cout << "Hello Earth." << endl;


/*[[[cog

print("""\
cout << "Hello Mars." << endl;
printf("Goodbye Pluto.\\n");
""")

]]]*/

//[[[end]]]


  return 0;
}

Notice that newlines have to be escaped.

Translate:

$ cog.py hello_world.cpp.cog > hello_world.cpp

Output:

using namespace std;

#include <iostream>

int main() {
    cout << "Hello Earth." << endl;


/*[[[cog

print("""\
cout << "Hello Mars." << endl;
printf("Goodbye Pluto.\\n");
""")

]]]*/
cout << "Hello Mars." << endl;
printf("Goodbye Pluto.\n");

//[[[end]]]


  return 0;
}

General build and run:

$ g++ -o hello_world hello_world.cpp
$ ./hello_world
Hello Earth.
Hello Mars.
Goodbye Pluto.

8 thoughts on “Cog: Evaluate Arbitrary Python Fragments in a Template Document

  1. I was wondering how to cog the file? since the cog will be in a c++ file format – do I call the file through python? I am using jetbrains so if you can help would be amazing

    Like

    • You would install and run the “cog” tool on the file to translate all of the Cog stuff. Then, you would build the C++ file like normal. I’ve updated the example.

      Like

      • I have the the cog tool install in jetbrains so would I run it from the command line in jetbrains pycharm?

        I a python script that parses an xml file and I have a template.h I want coh in my header template file to get my values from my dictionary and print them out. I have a python script that does this.

        So I would just need to run python cogapp template.h.cog > template.h

        correct?

        Like

      • It shouldn’t be automatic in this context. Since translating the template eliminates the template, you’d have to maintain one file with the template and another file with the result. It would likely lead to confusing, hidden magic (files changing for no apparent reason, files changing unexpectedly, files being changed but not committed, etc..) in the context of an IDE. Just call the one or more Cog calls that you might require from a script and call and commit the changes whenever you update the templates.

        For any further comments, please post a question on StackOverflow.

        Like

Comments are closed.