[英]Python import issue for different subpackages
I am trying to implement following hierarchy. 我正在尝试实现以下层次结构。 My final goal is myscpt.sh should run from any folder
我的最终目标是myscpt.sh应该从任何文件夹运行
But I am getting import errors. 但是我收到导入错误。
What is the best approach to implement such type of hierarchical architecture? 实现此类分层体系结构的最佳方法是什么?
FooSoft
|
|-- foo/
|
|-- test.py
|
|-- common/
|
|-- utils/
|
|-- api/
|
|-- scripts/
|-- myscript.py
|
|-- bin/myscpt.sh
|
|-- etc/foo.conf
bin/myscpt.sh 斌/ myscpt.sh
/usr/bin/python /path/FooSoft/foo/script/myscript.py /path/FooSoft/etc/foo.conf
foo/script/myscript.py 富/脚本/ myscript.py
from ..common import *
from ..utils import *
from ..test import *
.
.
<Doing some stuff>
I am using .. import
in most of modules to avoid absolute path. 我在大多数模块中使用
.. import
以避免绝对路径。
Typically I resolve import errors by always using the package root as a reference. 通常,我总是通过将软件包根目录用作参考来解决导入错误。
First, I would include a setup.py file in the project root, and add in a minimal setuptools wrapper . 首先,我将在项目根目录中包含setup.py文件,并添加一个最小的setuptools包装器 。
python setup.py develop
Then you don't have to worry about where you run the script from. 然后,您不必担心从何处运行脚本。 Your imports become as follows:
您的导入内容如下:
from foo.common import *
from foo.utils import *
from foo.test import *
Explicit relative imports with leading dots like from ..common import anything
can be used only from a code that has been imported as a submodule of the package eg foo.scripts
, but not from the the code imported as __main__
script, even if the script path contains .../foo/scripts/...
. 带有类似
from ..common import anything
前导点的显式相对导入只能从已作为包的子模块导入的代码(例如foo.scripts
,但不能从作为__main__
脚本导入的代码中使用,即使该脚本路径包含.../foo/scripts/...
The main script must use absolute imports or it can be used as module by something like python -c "from foo.scripts import myscript; myscript.run()"
. 主脚本必须使用绝对导入,或者可以由
python -c "from foo.scripts import myscript; myscript.run()"
用作模块。 (install the foo or use PYTHONPATH=/path/FooSoft). (安装foo或使用PYTHONPATH = / path / FooSoft)。 See Intra-package References in the docs or a similar question .
请参阅文档中的“包装内参考 ”或类似问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.