简体   繁体   中英

Running a file via the interpreter changes current directory?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM