2

I am trying to write a piece of python code which will write a piece of CMake code ...

But when I get to the following phase:

def_desc = "blaa"
s = "    FILE(WRITE ${CONFIG_H} \"/* {0} */\\n\")\n".format(def_desc)

then python yells at me:

Traceback (most recent call last):
  File "/home/ferencd/tmp/blaa.py", line 2, in <module>
    s = "    FILE(WRITE ${CONFIG_H} \"/* {0} */\\n\")\n".format(def_desc)
KeyError: 'CONFIG_H'
[Finished in 0.0s with exit code 1]

I understood that somehow the interpreter thinks that {CONFIG_H} is supposed to mean a parameter from the parameter list of format ... but no, I'd really like to print out that into the output ... as it is.

How can I deal with this situation?

martineau
  • 119,623
  • 25
  • 170
  • 301
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167

2 Answers2

9

You need to escape brackets "}" if it uses not for format variable.

def_desc = "blaa"
s = "    FILE(WRITE ${{CONFIG_H}} \"/* {0} */\\n\")\n".format(def_desc)
Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159
5

you need to use double braces:

s = "    FILE(WRITE ${{CONFIG_H}} \"/* {0} */\\n\")\n".format(def_desc)

It is much easier, though, to use template library for stuff like this, like jinja or mako.

m.wasowski
  • 6,329
  • 1
  • 23
  • 30
  • It's easier to use a template library than `format` with a single parameter? I doubt it. Template libraries would have the same issue with escaping special characters. – interjay Dec 01 '15 at 12:44
  • @interjay it is easier to write cmake files (which OP mentioned is trying to do) with template library than assembling it line by line ;-) – m.wasowski Dec 01 '15 at 12:46
  • @m.wasowski I have just started learning python ... :) But thanks for mentioning the template libraries, I will research them out shortly! – Ferenc Deak Dec 01 '15 at 12:48