[Tutor] Configuaration files and paths?

Allen Fowler allen.fowler at yahoo.com
Fri Aug 7 01:23:55 CEST 2009





> > 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')
> 


That is really great.  Thank you.  

I wonder why something like this is not in the standard library.  Seems like an often needed function.


      



More information about the Tutor mailing list