zezollo
zezollo

Reputation: 5017

How to correctly setup a path relative to running script also in tests?

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:

So, what would be the best way to handle this?

Upvotes: 4

Views: 1975

Answers (1)

The Compiler
The Compiler

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

Related Questions