Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variables already defined in ConfigParser

I'm using ConfigParser in Python

config.ini is

[general]
name: my_name
base_dir: /home/myhome/exp

exe_dir: ${base_dir}/bin

Here I want exp_dir becomes /home/myhome/exp/bin not ${base_dir}/bin.

It means ${base_dir} would be substituted to /home/myhome/exp automatically.

like image 319
emeth Avatar asked Feb 15 '11 01:02

emeth


People also ask

What is ConfigParser ConfigParser ()?

ConfigParser is a Python class which implements a basic configuration language for Python programs. It provides a structure similar to Microsoft Windows INI files. ConfigParser allows to write Python programs which can be customized by end users easily.

How do I load an INI file in Python?

To read and write INI files, we can use the configparser module. This module is a part of Python's standard library and is built for managing INI files found in Microsoft Windows. This module has a class ConfigParser containing all the utilities to play around with INI files. We can use this module for our use case.

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.


1 Answers

You can use ConfigParser interpolation

On top of the core functionality, SafeConfigParser supports interpolation. This means values can contain format strings which refer to other values in the same section, or values in a special DEFAULT section. Additional defaults can be provided on initialization.

For example:

[My Section] 
foodir: %(dir)s/whatever 
dir=frob 
long: this value continues    
    in the next line 

would resolve the %(dir)s to the value of dir (frob in this case). All reference expansions are done on demand.

Your example becomes:

[general]
name: my_name
base_dir: /home/myhome/exp

exe_dir: %(base_dir)s/bin
like image 175
Rod Avatar answered Oct 14 '22 06:10

Rod