Python ConfigParser

Filed Under: Python

Python ConfigParser

Python ConfigParser module is an extremely important one when it comes to creating configurable applications.

To provide a quick summary, using configparser module, we can keep the configuration related to our application in a configuration file, anywhere in the system and access it inside our application.

So, if we suppose that we keep our database connection details in the config file, we just need to change them to make our application point to a completely new database. This means that we didn’t have to change anything in our application to do this!
python configparser

What can config file include?

Thie config files we create can contain integers, floating point values, and Booleans. Specifically, here are important points:

  • The config file sections can be identified by having lines starting with [ and ending with ]. Between square brackets, we can put the section’s name, which can be any character except square bracket itself.
  • Lines starting with ; or # are treated as comments and are not available programmatically.
  • The values are separated by a = or a :.

Let’s look at a sample config file as well which will clear things well.


# A comment which can contain anything.
[database_config]
url = http://localhost:3306/mysql/
username = root
; Consider hashing this password rather than
; keeping it as plain-text here
password = MY_PASSWORD

See, how easy was that! The values which can be used programmatically in above files are url, username and password.

Python Config Files

Let’s put these concepts into use with some code snippets.

Using config files

We will be creating a sample config file which looks like this:


# A comment which can contain anything.
[database_config]
url = http://localhost:3306/mysql/
username = root
; Consider hashing this password rather than
; keeping it as plain-text here
password = MY_PASSWORD

Make this file and name it database.config and keep it in the same directory as the program we write next:


from configparser import ConfigParser

parser = ConfigParser()
parser.read('database.config')

print(parser.get('database_config', 'url'))

Here, we first find the section and then we continue to providing the exact key which we need. This is even good in terms of code readability. Let’s see the output for this program:
python configparser example

This was pretty simple actually.

Checking if config file exist

Before using the key values in our program, it will always be better if we check if the config file exists at all. With this, we can integrate a much better error mechanism in our application and maybe, inform the user if config files are missing.

Let’s see the code snippet:


from configparser import ConfigParser
import glob

config_parser = ConfigParser()

files_to_find = ['database.config', 'does-not-exist.config']

found_files = config_parser.read(files_to_find)
missing_files = set(files_to_find) - set(found_files)

print('Found config files:  ', sorted(found_files))
print('Missing files     :  ', sorted(missing_files))

Let’s see the output for this program:
python config file parser if exists

Iterating over all values present

We can iterate over all the sections and values present in the config files to look for a particular value or do any other operations.

Let’s see the code snippet on how this can be done:


from configparser import ConfigParser

config_parser = ConfigParser()
config_parser.read('database.config')

for section_name in config_parser.sections():
    print('Section:', section_name)
    print('  Options:', config_parser.options(section_name))
    for key, value in config_parser.items(section_name):
        print('  {} = {}'.format(key, value))
    print()

Let’s see the output for this program:
python config files iterate properties

Checking if a section is present

Wouldn’t it be better if we could just provide a section key and check if the section is present or not? It is possible actually and that’s what we will do in next code snippet:


from configparser import ConfigParser

config_parser = ConfigParser()
config_parser.read('database.configdatabase.config')

for key in ['url', 'cluster-address', 'database_config']:
    print('{:<12}: {}'.format(key, config_parser.has_section(key)))

Let’s see the output for this program:
python configparser section exists

Checking if a value is present

Now, let’s directly check if the value is present or not. Let’s see the code snippet on how this can be done:


from configparser import ConfigParser

config_parser = ConfigParser()
config_parser.read('database.config')

find_sections = ['cluster-address', 'database_config']
find_options = ['url', 'some-option']

for section in find_sections:
    has_section = config_parser.has_section(section)
    print('{} section exists: {}'.format(section, has_section))
    for key in find_options:
        has_option = config_parser.has_option(section, key)
        print('{}.{:<12}  : {}'.format(section, key, has_option))
    print()

Let’s see the output for this program:
python config file example

Conclusion

In this post, we saw how we can use Python‘s configparser module to access config files and put it to use in our application.

Reference: API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages