Configparser: parsing error with missing values
I am using Python old fashioned configparser
module to read config files from filesystem.
To check if the custom config file is using the correct syntax, I compare all section keys and subsections to a referenced config file ref_config.ini
that contains all allowed section keys and subkeys with committed values.
Parsing a custom file doesn't really matter and works pretty well. However, reading the reference-config results in the ParsingError
following:
ParsingError: Source contains parsing errors: 'ref_config.ini'
[line 2]: 'rotations_to_simulate\n'
[line 3]: 'number_of_segments\n'
[line 4]: 'material_data\n'
[line 7]: 'rpm\n'
The file ref_config.ini
contains the following lines:
[GENERAL DATA]
rotations_to_simulate
number_of_segments
material_data
[TECHNICAL DATA]
rpm
To read the above config file I am using the following code:
#!/usr/bin/env python3
# coding: utf-8
import configparser
import os.path
def read_ref_config():
config = configparser.ConfigParser()
if not os.path.isfile('ref_config.ini'):
return False, None
else:
config.read('ref_config.ini')
return True, config
However, ommiting values in the config file should not raise a ParsingError as the docs says:
Values can be omitted, in which case the key / value separator can also be omitted.
[No Values] key_without_value empty string value here =
Update:
I just copied and pasted the contents of the given example from the docs into my file ref_config.ini
and got a similar ParsingError with NoValue keys containing no spaces:
ParsingError: Source contains parsing errors: 'ref_config.ini'
[line 20]: 'key_without_value\n'
Simple way:
configparser.ConfigParser(allow_no_value=True)
according to configparse docs
>>> import configparser
>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-external-locking
... old_passwords = 1
... skip-bdb
... # we don't need ACID today
... skip-innodb
... """
>>> config = configparser.ConfigParser(allow_no_value=True)
>>> config.read_string(sample_config)
>>> # Settings with values are treated as before:
>>> config["mysqld"]["user"]
'mysql'
>>> # Settings without values provide None:
>>> config["mysqld"]["skip-bdb"]
>>> # Settings which aren't specified still raise an error:
>>> config["mysqld"]["does-not-exist"]
Traceback (most recent call last):
...
KeyError: 'does-not-exist'