Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extended interpolation not working in configparser

I tried to use configparser module from standard library in python 3.6 or python 3.5.1

My ini file looks like this:

[common]
domain = http://some_domain_name:8888
about = about/
loginPath = /accounts/login/?next=/home
fileBrowserLink = /filebrowser
partNewDirName = some_dir

[HUE_310]
partNewFilePath = ${common:domain}

My "main" program looks like this:

from configparser import ConfigParser

parser = ConfigParser()
parser.read('configfile.ini')

lll = parser.get('HUE_310', 'partNewFilePath')
print(lll)

Instead http://some_domain_name:8888 I got ${common:domain}

I use Pycharm Community as my IDE. I use virtualenv.

I have no idea what is wrong with my code...

like image 286
heniekk Avatar asked Mar 16 '17 16:03

heniekk


People also ask

What is interpolation in ConfigParser?

Extended interpolation is using ${section:option} to denote a value from a foreign section. Interpolation can span multiple levels. For convenience, if the section: part is omitted, interpolation defaults to the current section (and possibly the default values from the special section).

What is config () in Python?

A Python configuration file is a pure Python file that populates a configuration object. This configuration object is a Config instance.

Is ConfigParser built in Python?

configparser comes from Python 3 and as such it works well with Unicode.

How parse config file in Python?

Read and parse one configuration file, given as a file object. Read configuration from a given string. Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section.


1 Answers

If you want extended interpolation, you have to create an instance of the configparser.ExtendedInterpolation class, by calling it, and then using that with the interpolation= keyword argument when you create the ConfigParser instance as shown below:

from configparser import ConfigParser, ExtendedInterpolation

parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read('configfile.ini')

lll = parser.get('HUE_310', 'partNewFilePath')
print(lll)  # -> http://some_domain_name:8888
like image 129
martineau Avatar answered Oct 01 '22 16:10

martineau