1

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.

Draineh
  • 599
  • 3
  • 11
  • 28
  • How are you running the scripts? If you are launching them from a terminal, are you running them both from the same working directory? – James Jan 02 '12 at 15:43
  • permissions for the files are identical and the application executing them at the moment is invoked as root as this is currently internal testing. @James, they were both being invoked by the same instance of the Python interpretor. As far as I can see there should be no difference between the two scripts in terms of their location and their relative location to the config file. – Draineh Jan 02 '12 at 16:22

1 Answers1

1

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.

tito
  • 12,990
  • 1
  • 55
  • 75
  • Thank you. This has worked perfectly, surprised I didn't come across this solution when searching originally. I have applied the same solution to the already working script as well for consistancy and all is still working. Thanks again – Draineh Jan 02 '12 at 16:23