[英]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.当我尝试
$> python ./tools/test.py
我收到一个导入错误,提示我无法导入在我调用 python 的目录中存在的模块。 However, I can import this module, $> python -c "import mod"
works.但是,我可以导入这个模块,
$> python -c "import mod"
可以工作。
I'm relying on the fact that ./
is (in effect) on the PYTHONPATH.我依赖于
./
是(实际上)在 PYTHONPATH 上的事实。
What is python doing to the python path when I run the interpreter on a script that exists in a different directory?当我在不同目录中存在的脚本上运行解释器时,python 对 python 路径做了什么? Is there a way to "lock" the current working directory so that I can get the import to work?
有没有办法“锁定”当前工作目录,以便导入工作?
My setup:我的设置:
./mod.py
: ./mod.py
:
x = 5 # just for demonstration purposes
./tools/test.py
: ./tools/test.py
:
from mod import x
# ... snip ... actual content
I am invoking python from the directory that contains mod.py
and tools/
:我从包含
mod.py
和tools/
的目录中调用 python :
$> 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.请注意,包含
mod.py
和tools
的当前目录不在我的 PYTHONPATH 中。
I'm relying on the fact that
./
is (in effect) on the PYTHONPATH.我依赖于
./
是(实际上)在 PYTHONPATH 上的事实。
It's not.它不是。 It's not on
PYTHONPATH
, and it's not on sys.path
.它不在
PYTHONPATH
,也不在sys.path
。 When you run a script by file path, it's the script's directory that gets added to sys.path
.当您按文件路径运行脚本时,脚本的目录会被添加到
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 .您可以在Python 命令行 docs 中查看为指定要运行的程序的每种方式添加到
sys.path
的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.