[英]Why do I get an ImportError when executing sys.path.append in a file but not in the Python console?
I'm trying to run a script that requires a package in another directory. 我正在尝试运行一个脚本,该脚本需要另一个目录中的软件包。
This works: 这有效:
execfile("../test.py")
when starting python in package parent directory execfile("../test.py")
sys.path.append("package parent")
while in the python interpreter and then calling execfile("test.py")
sys.path.append("package parent")
在python解释器中,然后调用execfile("test.py")
This doesn't work (gives an ImportError
): 这不起作用(给出
ImportError
):
python ../test.py
when in package parent directory python ../test.py
python test.py
when in script directory python test.py
The test.py
file contains the same sys.path.append
instruction I used in the interpreter. test.py
文件包含与解释器中相同的sys.path.append
指令。 Is there a difference between running it in the file or in the interpreter? 在文件或解释器中运行它是否有区别?
My directory structure: 我的目录结构:
The error message I get: 我收到的错误消息:
from package.stuff import SomeClass
从package.stuff导入SomeClass
ImportError: No module named package.stuffImportError:没有名为package.stuff的模块
A hint why the behavior from the interactive shell is different from script behavior can be found in the docs for sys.path
: 可以在
sys.path
的文档中找到有关交互式shell行为与脚本行为不同的提示:
As initialized upon program startup, the first item of this list,
path[0]
, is the directory containing the script that was used to invoke the Python interpreter.在程序启动时初始化后,该列表的第一项
path[0]
是包含用于调用Python解释器的脚本的目录。 If the script directory is not available (eg if the interpreter is invoked interactively or if the script is read from standard input),path[0]
is the empty string, which directs Python to search modules in the current directory first.如果脚本目录不可用(例如,如果交互式调用解释器或从标准输入中读取脚本),则
path[0]
为空字符串,该字符串将引导Python首先搜索当前目录中的模块。 Notice that the script directory is inserted before the entries inserted as a result ofPYTHONPATH
.注意,由于
PYTHONPATH
的结果,脚本目录已插入到插入的条目之前。
This should explain why executing from an interactive shell works. 这应该可以解释为什么从交互式外壳执行是可行的。 However, without further information it can only be guessed why the script fails.
但是,没有更多信息,只能猜测脚本为什么失败。
Setting PYTHONPATH
is essentially the same as updating sys.path
. 设置
PYTHONPATH
本质上与更新sys.path
相同。 On bash
this would be: 在
bash
上将是:
PYTHONPATH=/path/to/package1:/path/to/package2 python test.py
Check out this post and the docs for details. 查看这篇文章和文档以了解详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.