Python

Python Configparser Example

Configparser is a class of Python programming language that implements the basic configuration language. Its structure resembles the INI file in Microsoft Windows. This class allows writing python programs that can be customized by the users. It is server-side programming. It is a module from the Python standard library and it defines the functionality for the reading and writing of the configuration files. These types of files have “.ini” extensions.

The configparser module in Python is used to work with the configuration files. A configuration file contains the data like the features, options, parameters, and also applications. These files are arranged in the form of sections; each section can contain the information as the name-value pair for the configuration data. The sections of the config file are identified by looking at the starting and the ending lines. It uses square brackets [] to store the value. The information between these square brackets is the name of the section, and it contains any expression, argument except the square bracket itself.

All the options are written one by one on each line separately inside a section. The technique of writing the option is that the ‘option’ is written at the start. A colon is used, an equal sign too, to separate the values in different lines. A sample code for the configuration file having the section of “bug_tracker” and the three options will be seen.

  • [bug_tracker]
  • url = http://localhost:8080/bugs/
  • username = Aqsa
  • password = qwerty

Common Uses of Configparser

The most common use of configparser is to allow the user and the system admin/analyst to edit the file with a simple text editor to set the environment back, and then let the application read that file, and then parse it. Configuration files help to update the source code of any program. The data stored in the file has to be separated so that the developer focuses on the code development and is assured that the user is only allowed to touch the file at the time of updating the data.

The configparser module has a class configparser. It is responsible for parsing all the configuration files. And also used for managing the database. The data is accessed through the object, we can also update and then create a new file through that instance. The below-mentioned statement shows the object creation of that class.

# parser = configparser.ConfigParser()

Several methods are defined inside this class. Some of these methods are discussed here:

Section:  It returns all the section names of configuration.

Read_dict(): This function reads the configuration from the dictionary. The keys are also present inside. These keys are the section names. Whereas the values part contains the dictionaries with the keys and values that must be present in the section.

Items(): This function is known to return the resultant value in the form of tuples with name plus value, for every option of the section.

Getboolean(): It functions like the get() function to fetch the record. But the content is not returned as an output. It returns the value in the form of Boolean. Like it returns either false or true.

Remove_section(): This function removes the file section and all the options related to the section. This function is opposite to the function ‘remove_option’, as it removes the options from the section of a file.

Use the config files for implementation.

Example 1

We will create a sample config file that will look like.

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

We will name this file as “database. Config” and then we will place and save this file in the same directory where we will add more config files.

Now, we will use a Python tool that is ‘Spyder’ to execute the code. We will import the library of configparser and the module to compile and execute the code. Here, we will use a read function for the configparser to read the saved file.

# Parser.read(‘database.config’)

After applying this function, we will print the URL of the respective data file.

from configparser import ConfigParser

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

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

Open your Linux terminal and then run the below-mentioned command.

$ python configparser.py

The resultant snap shows the URL of the specified file stored.

Example 2

This example is used to check the existence of the specific code we need to use as an example.  Once the key values are sent and the configuration process is started, it is not possible to terminate it immediately in the case of Python. If the code is not present, an error occurs and stops the configuration of the whole process.

from configparser import ConfigParser

config_parser = ConfigParser()

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

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))

So before using the key values, it is a better approach to check the config file, whether it is present in its place or not. By using this, we can avoid the occurrence of errors. Or if we encounter any error, a much better error mechanism can be generated in the application, and then the user is also notified about the missing file.

A globe feature is also imported here. We will display the two files. One is found and the other is missing. After searching the specific file, we then find the missing one. It is done by subtracting the founded file from all the files, it will then mention the lost files.

# missing_files = set(files_to_find) - set(found_files/available files)

We will see the output from the Python.

The output obtained shows the file we have created earlier. Whereas the missing portion shows the file that is not present.

Example 3

This example deals with iterating over all the values present. The iteration involves all the values and the sections present in the config files to find the specific value or to perform any other operation according to the requirement.

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()

First, the file is read by the configparser and then we have used a FOR loop to print the sections and the options on separate lines. And again a FOR loop is used to print the key values by using the ‘item()’

# for key, value in config_parser.items(section_name):

Now, let us examine the output of the code.

This will show all the possible information of the file including the URL, username, password, as a result of FOR loop of items. Whereas the first loop will display the section value.

Example 4

In the previous part, we have checked if the file is present or not. But now we will check whether the section is present or not. It is better to check the section before the execution by providing just the section key. We will apply this to the 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)))

For the key, we will use URL, cluster-address, and the config file of the database. The output will be as under.

You can see that all the values are false. It means that the section was not present. If we did not check the availability of the section, there will be the possibility of errors to have occurred.

Conclusion

‘Python configparser example’ is an article that comprises the configparser purpose and the usage of this class. An object is very necessary for this purpose. Some important options are also discussed. File creation and execution through this class is also explained that will assist you for future perspective.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.