runtime location discovery
Jeff Shannon
jeff at ccvcorp.com
Mon Apr 1 19:05:14 EST 2002
In article <mailman.1017453478.23509.python-list at python.org>,
geoff at gerrietts.net says...
> The other night, I tried to put in a chunk of code that allowed the
> program to be executed from an arbitrary location (like a user's home
> directory) without previously knowing where we were installed
> (allowing the app to be installed wherever it seems most natural to
> the system administrator).
>
> The code I wrote did this:
> root_location = os.path.dirname(sys.argv[0])
This also suffers from the problem that, if you cd to the
directory that the script is in and then run it, sys.argv[0] will
not contain path information.
One solution that I've used, is to look at the __file__ attribute
of a module that I've imported, like so:
import MyModule
installdir = os.path.dirname(MyModule.__file__)
This will tell you the directory that MyModule.py is located in,
which you can arrange to be the directory that you're interested
in. ;) Be aware, though, that in your original script (with
__name__ == '__main__'), the __file__ attribute is undefined
(which is why I grab it from a module, instead of directly in the
executing script).
--
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list