Reputation: 8091
When I try to $> python ./tools/test.py
I get an import error that I cannot import a module that exists in the directory from which I am invoking python. However, I can import this module, $> python -c "import mod"
works.
I'm relying on the fact that ./
is (in effect) on the PYTHONPATH.
What is python doing to the python path when I run the interpreter on a script that exists in a different directory? Is there a way to "lock" the current working directory so that I can get the import to work?
My setup:
./mod.py
:
x = 5 # just for demonstration purposes
./tools/test.py
:
from mod import x
# ... snip ... actual content
I am invoking python from the directory that contains mod.py
and tools/
:
$> python -c "from mod import x" # works fine
$> python tools/test.py
Traceback (most recent call last):
File "tools/test.py", line 1, in <module>
from mod import x
ModuleNotFoundError: No module named 'mod'
Note that the current directory, which contains mod.py
and tools
is not on my PYTHONPATH.
Upvotes: 0
Views: 31
Reputation: 280181
I'm relying on the fact that
./
is (in effect) on the PYTHONPATH.
It's not. It's not on PYTHONPATH
, and it's not on sys.path
. When you run a script by file path, it's the script's directory that gets added to sys.path
. You can see what gets added to sys.path
for each way of specifying a program to run in the Python command line docs.
Upvotes: 1