Reputation: 65600
I'm struggling with Python paths. I want to be able to import a file from a directory. I can do this when it's available from the filesystem, but not when I'm relying on my PATH (update: or PYTHONPATH) to find it.
Here are the symptoms. First of all, check that my current directory is on my PATH:
(.venv)~/Dropbox/gds/myapp $ pwd
/Users/me/Dropbox/gds/myapp
(.venv)~/Dropbox/gds/myapp $ echo $PATH
... :/usr/local/go/bin:.:/Users/me/Dropbox/gds/myapp
And check that test/test_app
is where I think it is (and has an __init__.py
in the directory:
(.venv)~/Dropbox/gds/myapp $ ls tests/
__init__.py __pycache__ test_app.py test_views.py
Now check that Python can import test/test_app
from this directory:
(.venv)~/Dropbox/gds/myapp $ python
Python 3.4.2 (default, Jan 29 2015, 13:46:46)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tests
>>> import tests.test_app
>>> exit()
All good so far. Now move to a different directory, and see if I can import test/test_app
:
(.venv)~/Dropbox/gds/myapp $ cd ..
(.venv)~/Dropbox/gds $ python
Python 3.4.2 (default, Jan 29 2015, 13:46:46)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tests
>>> import tests.test_app
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'tests.test_app'
But /Users/me/Dropbox/gds/myapp
is on my PATH, and I can import the directory, so why can't I import this file?
UPDATE:
Thanks for the suggestions. Just tried doing export PYTHONPATH=$PYTHONPATH:/Users/me/Dropbox/gds/myapp
: but still see the same problem when I run Python.
Upvotes: 1
Views: 179
Reputation: 414825
There is probably another tests
Python package in sys.path
. Check tests.__file__
to confirm. To fix it, use more specific names e.g., myapp.tests
instead i.e., move tests
package inside myapp
Python package.
Upvotes: 1
Reputation: 57630
The directory needs to be in PYTHONPATH
, not PATH
(which is for regular non-Python command lookup).
Upvotes: 1
Reputation: 1124718
Python doesn't use PATH
. It uses the PYTHONPATH
variable to look up modules:
Augment the default search path for module files. The format is the same as the shell’s
PATH
: one or more directory pathnames separated byos.pathsep
(e.g. colons on Unix or semicolons on Windows).
PATH
is a variable used by your shell to look up binaries; only the format (how paths are specified and separated) is shared.
Upvotes: 0