Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigParser in python 3 vs python 2

I've been slowly making the transition from py2 -> py3 and I've run into an issue that I can't quite resolve (as trivial as I'm sure the problem is). When I execute the code below, the config file appears to have no sections :(

Where have I gone astray?

As a note, I did reuse this code from a python 2 script (replacing the old ConfigParser.SafeConfigParser with the new configparser.ConfigParser). I don't think this fact is relevant, but maybe it is? Clearly, I do not know :)

Here's the project/main.py

import inspect
import os
import utilities.utilities

def main():
    config_ini_path = os.path.abspath(inspect.getfile(inspect.currentframe()).split('.py')[0] + '_config.ini'
    print(config_ini_path)
    config = utilities.utilies.get_config(config_ini_path)
    print(config.sections())

if __name__ == "__main__":
    main()

Here's the project/utilities/utilities.py:

import os
import configparser
import inspect
import sys

def get_config(config_file_path=os.path.abspath(inspect.getfile(inspect.currentframe()).split('.py')[0]) + '_config.ini'):
    parser = configparser.ConfigParser()
    if os.path.exists(config_file_path):
        with open(config_file_path, 'r') as config_file:
            parser.read(config_file)
            return parser
    else:
        print('FAILED TO GET CONFIG')
        sys.exit()

def set_config(parser, config_file_path):
    if os.path.exists(config_file_path):
        with open(config_file_path, 'w') as config_file:
        parser.write(config_file)
    else:
        print('FAILED TO SET CONFIG')
        sys.exit()

And finally, here is the project/project_config.ini:

[logging]
json_config_path = /project/logging.json

Interestingly, if I add

config['logging'] = {'json_config_path':'project/other.json'}
utilities.utilities.set_config(config, config_ini_path)
print(config.sections())

The change will be written to the file, however, upon re-execution, it will not be recalled (as witnessed by .sections()).

I'm sure I am missing something simple! What gives?

like image 890
SolipsisticAltruist Avatar asked Oct 29 '22 23:10

SolipsisticAltruist


1 Answers

Turns out .read() accepts filenames, and .read_file() accepts filetypes. Originally, I was using .readfp(), but read_file() has replaced it in py3! Silly, silly me.

like image 79
SolipsisticAltruist Avatar answered Nov 15 '22 07:11

SolipsisticAltruist