Cog: Use Python in your source files to generate pieces of code

I noticed a command-line tool named Cog on HN a few months ago. It allows you to embed pieces of Python code within other languages, to generate whatever text you may need. It can be installed using pip install cog.

To use it you embed Python code generator between the [[[cog and ]]] delimiters. An explicit [[[end]]] is also needed, to delimit the section were the generated code should appear. The function cog.outl() prints a line into the source file:

! This is my Fortran file.

![[[cog
!import cog
!fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
!for fn in fnames:
!    cog.outl("subroutine %s()\nend subroutine" % fn)
!]]]
![[[end]]]

After running it through cog with the command

$ cog -o test.f90 test.f90.in

it gives you a file with the contents

! This is my Fortran file.

![[[cog
!import cog
!fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
!for fn in fnames:
!    cog.outl("subroutine %s()\nend subroutine" % fn)
!]]]
subroutine DoSomething()
end subroutine
subroutine DoAnotherThing()
end subroutine
subroutine DoLastThing()
end subroutine
![[[end]]]

Note that Fypp can also be used for such purposes, with a slightly different syntax, as it’s a fully-fledged preprocessor language:

#:set fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing']
#:for fn in fnames
  subroutine ${fn}$
  end surboutine
#:endfor
3 Likes