Search code examples
pythonpathconfigobj

ConfigObj and absolute paths


i'm having a bit of a path issue when using configobj for python. i'm wondering if there's a way to not use an absolute path in my helper file. For example, instead of:

self.config = ConfigObj('/home/thisuser/project/common/config.cfg')

i want to use something like:

self.config = ConfigObj(smartpath+'/project/common/config.cfg')

Background: i've placed my config file in a common directory along side a helper class and a utility class:

common/config.cfg
common/helper.py
common/utility.py

the helper class has a method that returns the values within the section of the config. the code is as such:

from configobj import ConfigObj

class myHelper:

    def __init__(self):
        self.config = ConfigObj('/home/thisuser/project/common/config.cfg')

    def send_minion(self, race, weapon):
        minion = self.config[race][weapon]
        return minion

the utility file imports the helper file and the utility file is called by a bunch of different classes stationed in different folders of my project:

from common import myHelper

class myUtility:

    def __init__(self):
        self.minion = myHelper.myHelper()

    def attack_with_minion(self, race, weapon)
        my_minion = self.minion.send_minion(race, weapon)
        #... some common code used by all
        my_minion.login()

the following files import the utility file and calls the method:

/home/thisuser/project/folder1/forestCastle.py
/home/thisuser/project/folder2/secondLevel/sandCastle.py
/home/thisuser/project/folder3/somewhere/waterCastle.py

self.common.attack_with_minion("ogre", "club")

if i don't use an absolute path and i run forestCastle.py it looks for the config in /home/thisuser/project/folder1/ and i want it to look for it in project/common/ because /home/thisuser will change


Solution

  • You can calculate a new absolute path based on a module filename instead:

    import os.path
    from configobj import ConfigObj
    
    BASE = os.path.dirname(os.path.abspath(__file__))
    
    
    class myHelper:
    
        def __init__(self):
            self.config = ConfigObj(os.path.join(BASE, 'config.cfg'))
    

    __file__ is the filename of the current module, so for helper.py that would be /home/thisuser/project/common/helper.py; os.path.abspath() makes sure it is a absolute path, and os.path.dirname removes the /helper.py filename to leave you with an absolute path to the 'current' directory.