SoFunction
Updated on 2024-11-14

Python using configuration file process in detail

This article introduces the use of python configuration file process in detail, the text through the sample code is very detailed, for everyone's learning or work has a certain reference value of learning, you can refer to the following friends

Expose variables to user modification via configuration files

Standard library module configparser so that standard formats can be used in configuration files.

Configuration files must be divided into sections using headings such as [files], [colors], and so on. The names of the headings can be specified freely, but they must be enclosed in square brackets.

$ cat 

[numbers]
pi: 3.1415926535893971

[messages]
greeting: Welcome to the area calutation program!
question: plse enter the radius
result_message: The area is

Use python to read him.

from configparser import ConfigParser
CONFIGFILE = ""

config = ConfigParser()
# Read the configuration file
(CONFIGFILE)

print(config['messages'].get('greeting'))

radius = float(input(config['messages'].get('question') + ' '))

# End with a space to continue printing on the current line:
print(config['messages'].get('result_message'),end=' ')
print(config['numbers'].getfloat('pi') * radius**2)

The following three sources of configuration or control information are available, and you should query these sources in the order in which they are listed here, allowing later sources to override earlier ones:
1, Configuration file

2, Environment Variables

3, switches and parameters passed to the program in the command line: to deal with command line parameters, can be used directly; to deal with switches (options), should use the module argparse

This is the whole content of this article.