Reputation: 5017
In order to set some paths to access subdirectories of my app (like locale/
), I use this in a settings.py
:
__process_name = os.path.basename(sys.argv[0])
__abspath = os.path.abspath(sys.argv[0])
__l1 = len(__process_name)
__l2 = len(__abspath)
rootdir = __abspath[:__l2-__l1]
And then, for instance to access data/
:
datadir = rootdir + "data/"
Problem is, when I run this settings.py
when I run the tests (e.g. python3 -m py.test
), then sys.argv[0]
doesn't match myapp anymore and the tests script can't access data/
.
I wonder how to deal with this, for instance:
settings.py
for my app only, and provide the tests suite with the correct (hardcoded) rootdir?installdir
in a configuration file, that would be setup during installation and then used by both my app (instead of the snippet above) and its tests suite?sys.argv[0]
by 'myappname'
, but, as there are different directories having the same name, it's not sure it gets the right one. (Plus, what if there is one installed version and one dev version at another place: how to make the distinction between them?)So, what would be the best way to handle this?
Upvotes: 4
Views: 1975
Reputation: 11929
So the usual thing to do is os.path.dirname(os.path.abspath(__file__))
.
__file__
is the path to the current module, os.path.abspath
makes sure it's absolute, and os.path.dirname
gives you the directory part of it.
If you have a module as part of a package and need e.g. a directory in the package, you can either use os.path.join(..., os.pardir)
as appropriate, or if possible import the package (i.e. its __init__.py
) and do your_package.__file__
.
An alternative you might want to consider as well is specifying your data as package data using setuptools, and then using the pkg_resources
API to access it.
Upvotes: 6