Search code examples
pythoncronconfigparserpathlib

pathlib absolute path misbehaving with config parser


I have a following python3 script, that uses the config function to load data from a txt file that sits in the same directory where the script is located.

I've implemented the configparser module to extract the data, and pathlib module to set the absolute path to that file

from pathlib import Path

try:
    import ConfigParser as configparser
except:
    import configparser

def config():
    parser = configparser.ConfigParser()
    config_file = Path('config.txt').resolve()
    parser.read(config_file)
    return parser

then i pass it as an argument to the next method, which then gets the needed variables from the config file:

def search_for_country(config):
    country_name = config.get("var", "country_name")

the config.txt file is structured like this:

[var]
country_name = Brazil

The problem is: everything works fine if I run the script via Terminal from the same directory, but eventually it is intended to be run as a cron job, and if i try to execute it from one directory above, it returns the following error:

File "test/script.py", line 28, in search_for_country
    country_name = config.get("var", "country_name")
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/configparser.py", line 781, in get
    d = self._unify_values(section, vars)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/configparser.py", line 1149, in _unify_values
    raise NoSectionError(section) from None
configparser.NoSectionError: No section: 'var'

Which seems to be telling that it cannot find the txt file.

So far I've tried out different options, for example using parser.read_file() instead of parser.read(), also tried this: https://stackoverflow.com/a/35017127/13363008

But none seem to be working. Maybe anyone could think of a cause to this problem?


Solution

  • so for Your problem :

    import pathlib
    
    path_own_dir = pathlib.Path(__file__).parent.resolve()
    path_conf_file = path_own_dir / 'config.txt'
    assert path_conf_file.is_file()
    
    

    but why to store such config as text in the first place ? "config is code" - so why limit Yourself with text config files ?

    my usual way is :

    # conf.py
    class Conf(object):
        def __init__(self):
            country_name: str = 'Brazil'
    
    conf=Conf()
    
    # main.py
    
    from .conf import conf
    
    print(conf.county_name)
    
    # override settings in the object
    conf.county_name = 'Argentina'
    
    print(conf.county_name)
    
    

    it has so many advantages like having the correct data type, having the IDE hints, avoiding the parsers, dynamically change settings, etc ...