configparser: parsing error with omitted values

5.7k views Asked by At

I'm using Python's old-fashioned configparser module to read config-files from the filesystem.

To check whether a user-provided config-file uses correct 'syntax' I compare all section keys and subkeys to a reference config-file ref_config.ini containing all allowed section keys and subkeys with ommited values.

Parsing the user-specific file is not a big deal and works pretty well. However, reading the reference-config leads to a ParsingError as follows:

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 of the following lines:

[GENERAL DATA]
rotations_to_simulate
number_of_segments
material_data

[TECHNICAL DATA]
rpm

To read the above mentioned config-file I use 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 a config file should not cause a ParsingError since the docs tell:

Values can be omitted, in which case the key/value delimiter may also be left out.

[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 ref_config.ini file and got a similar ParsingError with NoValue-keys not containing any whitespaces:

ParsingError: Source contains parsing errors: 'ref_config.ini'
    [line 20]: 'key_without_value\n'
1

There are 1 answers

0
LittleQ On BEST ANSWER

The easy 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'