问题描述
这个问题详细说明了我无法向自己解释的行为.
This questions is detailing a behavior that I can't explain to myself.
src/package/__init__.py
为空但存在.
src/package/subpackage/__init__.py
:
pink = 'It works'
src/package/test/test.py
:
import package.subpackage as subpackage
# I also tried `import package.subpackage as subpackage
print subpackage.pink
从src
呼叫:python package/test/test.py
只是失败,并显示ImportError: No module named subpackage
.请注意,import package
也不起作用.
Calling from src
: python package/test/test.py
just fails with ImportError: No module named subpackage
. Please note that import package
doesn't work either.
注意:(从src
运行解释器并键入import语句非常好.
NB: (Running an interpreter from src
and typing the import statement works perfectly well.
我应该理解我不应该调用程序包的子文件吗?在我的项目中,这是一个测试文件,因此在这里存放它听起来很合逻辑.
Should I understand that I'm not suppose to call subfile of a package? In my project it's a test file so it sounds logical for me have it here.
为什么当前工作目录不在导入路径中?
Why the current working directory is not in the import path?
非常感谢那些阅读和回答的人.
Many thanks for those who reads and those who answers.
推荐答案
因为您的软件包不在$ PYTHONPATH中.如果要调用test.py,则可以将test.py文件移动到src/目录,或将src添加到$ PYTHONPATH
Because you package is not in $PYTHONPATH. If you what to call test.py, you can move your test.py file to src/ directory, or add src to $PYTHONPATH
PYTHONPATH="/path/to/src:$PYTHONPATH"
export PYTHONPATH
来自文档
>>> import sys
>>> sys.path
输出是这样的
['.', '/usr/bin', ...
这意味着当前目录也位于sys.path中.如果要导入模块,请通过将软件包目录添加到环境变量PYTHONPATH或将当前目录或脚本目录更改为软件包目录来确保模块路径在sys.path中.
This means that the current directory is in sys.path as well. If you want to import a module, please make sure that the module path is in sys.path, by adding your package directory to the environment variable PYTHONPATH, or changing your current directory or script directory to the package directory.
这篇关于Python路径说明:从子包导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!