Search code examples
pythonconfigurationconfigparser

Python - Script execution, locationing errors


Using the ConfigParser module I am attempting to read in a configuration file so I can safely allow users to edit settings for an application and share these configurations between scripts. This has been working perfectly for the main script. However there is a secondary script that is called and it reads the same configuration file in the same location but returns an error that the location cannot be found. Both scripts are located within the same directory, application/bin/ The configuration file is located in application/conf/ To reference the config file successfully in the main script I use the following code which works perfectly.

config = ConfigParser.ConfigParser()
config.readfp(open('../conf/settings.conf'))

When the secondary script executes with the same code it reports that the location does not exist? I used the logger module and got it to log sys.path[0] which correctly returned the same bin folder as the main script. Is there possibly something simple I am missing here?

Also any troubleshooting tips for problems like these are welcome.


Solution

  • You can prefer to use dirname and __file__:

    from os.path import dirname, join
    config = ConfigParser.ConfigParser()
    config_fn = join(dirname(__file__), '..', 'conf', 'settings.conf')
    config.read(config_fn)
    

    Depending how you're launching the app (python bin/app.py, or python app.py), the '..' will be incorrect. By starting from the directory of the .py file, you'll always be able to construct the path from the .py to the .conf using that method.