I've used ConfigParser for quite a while for simple configs. One thing that's bugged me for a long time is the DEFAULT section. I'm not really sure what's an appropriate use. I've read the documentation, but I would really like to see some clever examples of its use and how it affects other sections in the file (something that really illustrates the kind of things that are possible).
The configparser module from Python's standard library defines functionality for reading and writing configuration files as used by Microsoft Windows OS. Such files usually have . INI extension.
A configuration file, often shortened to config file, defines the parameters, options, settings and preferences applied to operating systems (OSes), infrastructure devices and applications in an IT context. Software and hardware devices can be profoundly complex, supporting myriad options and parameters.
In computing, configuration files (commonly known simply as config files) are files used to configure the parameters and initial settings for some computer programs. They are used for user applications, server processes and operating system settings.
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.
I found an explanation here by googling for "windows ini" "default section". Summary: whatever you put in the [DEFAULT] section gets propagated to every other section. Using the example from the linked website, let's say I have a config file called test1.ini:
[host 1] lh_server=192.168.0.1 vh_hosts = PloneSite1:8080 lh_root = PloneSite1 [host 2] lh_server=192.168.0.1 vh_hosts = PloneSite2:8080 lh_root = PloneSite2
I can read this using ConfigParser:
>>> cp = ConfigParser.ConfigParser() >>> cp.read('test1.ini') ['test1.ini'] >>> cp.get('host 1', 'lh_server') '192.168.0.1'
But I notice that lh_server is the same in both sections; and, indeed, I realise that it will be the same for most hosts I might add. So I can do this, as test2.ini:
[DEFAULT] lh_server=192.168.0.1 [host 1] vh_root = PloneSite1 lh_root = PloneSite1 [host 2] vh_root = PloneSite2 lh_root = PloneSite2
Despite the sections not having lh_server keys, I can still access them:
>>> cp.read('test2.ini') ['test2.ini'] >>> cp.get('host 1', 'lh_server') '192.168.0.1'
Read the linked page for a further example of using variable substitution in the DEFAULT section to simplify the INI file even more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With