SoFunction
Updated on 2024-10-29

Python interface automation ConfigParser configuration file use details

Preface: the vast majority of computer programs we use today, whether it's office software, browsers, or even games and videos are systematically configured through a menu interface, and it's pretty much become the default way we use our machines. And in python, there is such a configuration module to make code configurable.

What is a configuration file

The configuration file here is different from the visual menu interface we usually see, it is like the code form, as in the following example:

❓ Why profile?

✔️ makes both code and configuration modularizable and configurable to improve the reusability of code, so when to make it configurable? Multiple places are used in a parameter, often change the parameters, etc., can be configurable, we only need to modify the configuration file can be, do not need to repeat the changes in the code in a place.

Python provides a ConfigParser module that implements a basic configuration file parser language that provides constructs similar to the.inistructure in the file. Common configuration file formats are.ini.conf.cfgThe configuration file consists of two file objects: section and option. A configuration file can contain one or more sections, and each section can have multiple options (key=value), as indicated in the figure above.

Read configuration file

It is the same as file file, you need to open it before you can read the operation, the common methods are as follows:

  • read(filename): Read the contents of the configuration file directly
  • sections(): Returns all sections as a list
  • options(section): get all the options under the corresponding section
  • items(section): get all key-value pairs under the corresponding section
  • get(section,option): Get the value of the option in the corresponding section and return it as a string.
  • getint(section,option): gets the value of the option in the corresponding section and returns it as an int.

In the figure aboveAn example of a read operation:

from configparser import ConfigParser

# Create an object that operates on configuration files (file parsing object)
conf = ConfigParser()

# Read the configuration file
("", encoding="utf8")
# Get all sections
res2 = ()
print("this isres2:{}\n".format(res2))
# Get the option under the corresponding section
res3 = ("logging")
print("this isres3:{}\n".format(res3))
# Get all key-value pairs under the corresponding section
res4 = ("logging")
print("this isres4:{}\n".format(res4))
# get method: read out content, are strings
res5 = ("logging", "level")
print("this isres5:{}".format(res5), type(res5))
# getint method: read out the content, are int type
res6 = ("mysql", "port")
print("\nthis isres6:{}".format(res6), type(res6))

Run results:

C:\software\python\ D:/learn/
This is res2: ['logging', 'mysql']

This is res3: ['level', 'f_level', 's_level']

This is res4: [('level', 'DEBUG'), ('f_level', 'DEBUG'), ('s_level', 'ERROR')]

This is res5: DEBUG <class 'str'>

This is res6: 3306 <class 'int'>

Process finished with exit code 0

In addition to read str, int type, but also supports float, boolean, here will not be an example.

🎈 Trivia:

  • Key-value pairs available=Also available:separate
  • sectionNames are case-sensitive, whereas options are not.
  • In key-value pairs, any whitespace at the beginning and end will be removed.
  • Comments can also be written in the configuration file.#or;prefix

Write Configuration File

The basic write method is as follows:

add_section(section) : Add a new sectionset( section, option, value) : To set the option in a section, you need to call write to write the content to the configuration file.

from configparser import ConfigParser

# Create an object that operates on configuration files (file parsing object)
conf = ConfigParser()
conf.add_section('test')
('test', 'name', 'Amy')
(open('', "a", encoding="utf-8"))

View after runninginside the file:

ConfigParser encapsulation

Wrap it up once and for all, and call it up directly afterward, wrapping content on demand.

from configparser import ConfigParser


class MyConf:

  def __init__(self, filename, encoding="utf8"):
     = filename
     = encoding
     = ConfigParser()
    (filename, encoding)

  def get_str(self, section, option):
    return (section, option)

  def get_int(self, section, option):
    return (section, option)

  def get_float(self, section, option):
    return (section, option)

  def get_bool(self, section, option):

  def write_data(self, section, option, value):
    (section, option, value)
    (open(, "a", encoding=))
    

if __name__ == '__main__':
  print(conf.get_str("", "test","name"))	# beta (software)

summarize

to this article on the use of python interface automation ConfigParser configuration file is introduced to this article, more related to python interface automation ConfigParser configuration file content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!