How to escape a % sign in a configobj value?

Helmut Grohne picture Helmut Grohne · Oct 28, 2010 · Viewed 8.4k times · Source

I'd like to use both parse time and runtime interpolation for values of a configobj configuration file. The easiest way to do simple string interpolation in Python is "%(foo)s" % somedict. Unfortunately configobj uses the same interpolation mechanism and I have not yet found a way to escape it. Ideally my value would look like:

othervar = foo
someconfigobjkey = %(othervar)s %%(runtimevar)s

However configobj tries (and fails) to replace the second variable. Another way to answer this question is to provide a different (configobj) way to do both parse time and runtime interpolation.

Answer

Huercio picture Huercio · Jul 7, 2015

Things may have changed since this question was posted, but I've discovered that you can escape using the '%' char. This worked for me in Python 3.

In my config.ini file:

[LOGGING]
format = %%(asctime)-15s %%(message)s

In my python script file:

import configparser

# Load configuration
config = configparser.ConfigParser()
config.read("config.ini")

log_config = config['LOGGING']

print(log_config['format']) # prints out '%(asctime)-15s %(message)s'

Hope it helps someone in the future (: