[Tutor] Configuaration files and paths?

Martin Walsh mwalsh at mwalsh.org
Thu Aug 6 21:29:57 CEST 2009


Allen Fowler wrote:
> 
> 
> 
>>> What is the recommended way to configure my application find the various 
>> database and/or configuration files it needs?
>>
>> Recommemded by whom? A lot depends on the OS. Apple for example have one set of 
>> recommendations for MacOS, Windows has another and Linux has several to choose 
>> from!
>>
> 
> 
> Thank you.... good point.
> 
> Planning on using a ConfigParser based .ini file located in the ./config folder.
> 
>>> For instance my folder layout:
>>>
>>> /path_to_app/app.py
>>> /path_to_app/lib/
>>> /path_to_app/database/
>>> /path_to_app/config/
>>> /path_to_app/photos
>>>
>>> .... and so on.  I would like to make an .ini in the config folder 
>> Seems fair enough, however on a Unix system you should also consider allowing 
>> the user to have their own personalised version in their home directory. Thus at 
>> startup you get the current user ID / home directory and look for a suitable 
>> config file. If it exists read it, if not read the default one in your config 
>> directory.
>>
>>> 1) How does my main app file find the config file in the first place?
>> Generally use a relative path so normally your app will run from its home folder 
>> so you can look in ./config. You might also set a system environment variable - 
>> for example the CLASSPATH or PYTHONPATH variables, or the ORACLE_HOME used by 
>> Oracle for their database. If the environment var is not set then look in 
>> ./config
>>
> 
> Assuming the application could be invoked in odd ways that may alter the notion of the current working directory, how do I unambiguously find the absolute path to the current python source file?  (So I can load the nearby .ini)

I use a helper function that calculates the absolute path of my app
script, then I am able to os.path.join relative elements to my heart's
content. I haven't had a problem with this approach so far, which of
course doesn't mean it's the right way, or even a correct implementation
for that matter.

Something like this ...

# lib/mypaths.py
# --------------

import os

def script_path(base):
    return os.path.realpath(os.path.abspath(base))

def script_dir(base):
    return os.path.dirname(script_path(base))

def join_relative(base, path):
    return os.path.join(script_dir(base), path)

# app.py
# ------

...

from lib.mypaths import join_relative
print join_relative(__file__, 'config/prefs.ini')

# this may work when calling from
# other modules, I suppose (untested)

import sys
print join_relative(sys.argv[0], 'config/prefs.ini')

...


HTH,
Marty


More information about the Tutor mailing list