ConfigParser module of python - configure parser

brief introduction

The configparser module is modified as configparser in Python 3 This module defines a configparser class. The function of this class is to use the configuration file to take effect. The format of the configuration file is the same as that of the INI file of windows

The function of this module is to create an object by using the three methods of RawConfigParser(), ConfigParser(), and SafeConfigParser() in the module (one out of three), and use the method of the object to add, delete, and modify the specified configuration file.

The configuration file has different fragment composition, which is similar to the format in the repo file in Linux:

Format:

1 [section] 
2 name=value perhaps name: value
3 "#"And"; "Indicates a comment
4 section It can be understood as a module, such as when logging in section Can call login,It's down there username and password
5 [DEFAULT] #Set the default variable value and initialize
1 [My Section]
2 foodir: %(dir)s/whatever
3 dir=frob
4 long: this value continues
5    in the next line

%(dir)s , will be replaced by frob. The default value is passed to the constructor of ConfigParser in the form of a dictionary. section is generally stored in the built-in directory. If you switch to another directory, you need to specify the storage location.

method

Remember to pay attention to the following three methods

When calling these three functions, keep in mind that these three functions will call optionxform(). When passing key value pair data, all key names will be converted to lowercase.

RawConfigParser()

'''
No one answers any questions? Xiaobian created a Python exchange of learning QQ Group: 857662006 
Look for like-minded partners to help each other,There are also good videos and tutorials in the group PDF e-book!
'''
1 ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]]) 
2 
3 defaults : If a default value is specified, the key value pair of the default value is used
4 dict_type: Use new section Key value pair
5 allow_no_value : Default is False,If it is True,Indicates that null values can be received( None)
6 return: object

Variable parameters are not supported, and% () s cannot exist in section

ConfigParser()

1 ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]]) 

% () s must appear in default

SafeConfigParser()

 ConfigParser.SafeConfigParser([defaults[, dict_type[, allow_no_value]]]) 

More intelligent. Whether there is% () s in the section will be judged automatically

The passed parameters use the function optionxform(), foo% (bar) s and foo% (bar) s are the same, and optionxform() will convert all uppercase letters to lowercase letters.

Common anomalies

abnormaldescribe
ConfigParser.ErrorBase class for all exceptions
ConfigParser.NoSectionErrorThe specified section was not found
ConfigParser.DuplicateSectionErrorCall add_ The section name has already been used when using section()
ConfigParser.NoOptionErrorThe specified parameter was not found
ConfigParser.InterpolationErrorWhen there is a problem when performing string interpolation, the base class with exception occurs
ConfigParser.InterpolationDepthErrorWhen the string interpolation cannot be completed, it cannot be completed because the number of iterations exceeds the maximum range. Subclass of InterpolationError
InterpolationMissingOptionErrorAn exception occurs when the referenced option does not exist. Subclass of InterpolationError
ConfigParser.InterpolationSyntaxErrorAn exception occurs when the source text that produces the replacement does not conform to the required syntax. Subclass of InterpolationError.
ConfigParser.MissingSectionHeaderErrorAn exception occurs when trying to parse a file without a segmented title.
ConfigParser.ParsingErrorAn exception occurs when an error occurs while trying to parse a file
ConfigParser.MAX_INTERPOLATION_DEPTHWhen the raw parameter is false, the maximum depth of recursive interpolation of get(). This applies only to the ConfigParser class

RawConfigParser object

The operation of objects can be divided into two categories: one is the operation of configuration files, and the other is the operation of read data streams.

Operations on configuration files

Read configuration file

methoddescribe
read(filenames)filesnames is a list. Applications that need to load initial values from files should use readfp() to load the required files or files before calling read().
readfp(fp[, filename])In fp, read and parse configuration data from files or file class objects (using only the readline() method). If the file name is omitted and fp has a name attribute, it is used for the file name; The default value is <? >.

Write configuration file

methoddescribe
write(fileobject)Writes the configured representation to the specified file object. This representation can be parsed by future read() calls.

Operations on data streams in memory

Increase the value in the configuration file

methoddescribe
add_section(section)Add a section to the instance

Delete the value in the configuration file

methoddescribe
remove_option(section, option)Removes the specified option from the specified section. If this part does not exist, please raise NoSectionError. If the existing options are deleted, return True; Otherwise, False is returned.
remove_section(section)Deletes the specified section from the configuration. Returns True if this part does exist. Otherwise, false is returned

Modify the value in the configuration file

methoddescribe
set(section, option, value)If the given part exists, set the given option to the specified value
optionxform(option)You can also reset it on an instance, for a function that requires string parameters. For example, setting it to str makes option names case sensitive

Find values in configuration files

methoddescribe
defaults()Returns the dictionary containing the default value of the instance scope.
sections()Return the list of available sections; The default section is not included in the list
has_section(section)Indicates whether the specified section appears in the configuration. The default section is not confirmed
options(section)Returns a list of options available in the specified section.
has_option(section, option)If the given section exists and contains the given options, return True; Otherwise, False is returned
get(section, option)Gets an option value for the specified section.
getint(section, option)It casts the options in the specified section to an integer
getfloat(section, option)It casts the options in the specified section to floating point
getboolean(section, option)Cast to Boolean, "1", "yes", "true", and "on", cast to true, "0", "no", "false", and "off", cast to false, others return ValueError
items(section)Returns a list of (name,value) pairs for each option in a given section.
methoddescribe
1 import ConfigParser, os
2 
3 config = ConfigParser.ConfigParser()
4 config.readfp(open('defaults.cfg'))
5 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
1 cfgparser = ConfigParser()
2 ...
3 cfgparser.optionxform = str

ConfigParser object

SafeConfigParser contains the same methods as ConfigParser and some additional methods

methoddescribe
get(section, option[, raw[, vars]])Gets an option value for the specified section. If vars is provided, it must be a dictionary. This option is found in vars (if provided), segments, and defaults,
items(section[, raw[, vars]])Returns a list of (name, value) pairs for each option in a given section

All '%' interpolation is expanded in the return value unless the original parameter is true. The value of the interpolation key is the same as the option

SafeConfigParser object

set(section, option, value) 

If the given part exists, set the given option to the specified value; Otherwise, increase NoSectionError. The value must be a string (str or unicode); If not, a type error occurs

example

Example 1: write configuration file

 1 import ConfigParser
 2 
 3 config = ConfigParser.RawConfigParser()
 4 
 5 # When adding sections or items, add them in the reverse order of
 6 # how you want them to be displayed in the actual file.
 7 # In addition, please note that using RawConfigParser's and the raw
 8 # mode of ConfigParser's respective set functions, you can assign
 9 # non-string values to keys internally, but will receive an error
10 # when attempting to write to a file or when you get it in non-raw
11 # mode. SafeConfigParser does not allow such assignments to take place.
12 config.add_section('Section1')
13 config.set('Section1', 'an_int', '15')
14 config.set('Section1', 'a_bool', 'true')
15 config.set('Section1', 'a_float', '3.1415')
16 config.set('Section1', 'baz', 'fun')
17 config.set('Section1', 'bar', 'Python')
18 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
19 
20 # Writing our configuration file to 'example.cfg'
21 with open('example.cfg', 'wb') as configfile:
22     config.write(configfile)

Example 2: reading configuration files

'''
 1 import ConfigParser
 2 
 3 config = ConfigParser.RawConfigParser()
 4 config.read('example.cfg')
 5 
 6 # getfloat() raises an exception if the value is not a float
 7 # getint() and getboolean() also do this for their respective types
 8 a_float = config.getfloat('Section1', 'a_float')
 9 an_int = config.getint('Section1', 'an_int')
10 print a_float + an_int
11 
12 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
13 # This is because we are using a RawConfigParser().
14 if config.getboolean('Section1', 'a_bool'):
15     print config.get('Section1', 'foo')

Example 3: get the insertion value

 1 import ConfigParser
 2 
 3 config = ConfigParser.ConfigParser()
 4 config.read('example.cfg')
 5 
 6 # Set the third, optional argument of get to 1 if you wish to use raw mode.
 7 print config.get('Section1', 'foo', 0)  # -> "Python is fun!"
 8 print config.get('Section1', 'foo', 1)  # -> "%(bar)s is %(baz)s!"
 9 
10 # The optional fourth argument is a dict with members that will take
11 # precedence in interpolation.
12 print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
13                                         'baz': 'evil'})

Example 4: default value

All three types of config analyzers can use default values. If an option is not defined elsewhere, they are used for interpolation

 1 import ConfigParser
 2 
 3 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
 4 config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
 5 config.read('example.cfg')
 6 
 7 print config.get('Section1', 'foo')  # -> "Python is fun!"
 8 config.remove_option('Section1', 'bar')
 9 config.remove_option('Section1', 'baz')
10 print config.get('Section1', 'foo')  # -> "Life is hard!"

Example 5: move options between section s

1 def opt_move(config, section1, section2, option):
2     try:
3         config.set(section2, option, config.get(section1, option, 1))
4     except ConfigParser.NoSectionError:
5         # Create non-existent section
6         config.add_section(section2)
7         opt_move(config, section1, section2, option)
8     else:
9         config.remove_option(section1, option)

Example 6: there is a null value in the configuration file

Some configuration files contain settings without values, but it is consistent with the syntax supported by ConfigParser. The disallowed value parameter to the constructor can be used to indicate that such a value should be accepted

>>> import ConfigParser
>>> import io

>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-external-locking
... old_passwords = 1
... skip-bdb
... skip-innodb
... """
>>> config = ConfigParser.RawConfigParser(allow_no_value=True)
>>> config.readfp(io.BytesIO(sample_config))

>>> # Settings with values are treated as before:
>>> config.get("mysqld", "user")
'mysql'

>>> # Settings without values provide None:
>>> config.get("mysqld", "skip-bdb")

>>> # Settings which aren't specified still raise an error:
>>> config.get("mysqld", "does-not-exist")
Traceback (most recent call last):
  ...
ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'

Keywords: Python Testing

Added by Moocat on Sun, 06 Feb 2022 23:01:31 +0200