Python 如何从“包内”导入包模块;“主要”;模块

Python 如何从“包内”导入包模块;“主要”;模块,python,Python,我的包结构是: main.py mapp/ __init__.py core/ __init__.py tobeimported.py test/ __init__.py (test modules) utils/ __init__.py blasttofasta.py 但例外情况是: Traceback (most recent call last): File "utils/blasttofasta.py

我的包结构是:

main.py mapp/ __init__.py core/ __init__.py tobeimported.py test/ __init__.py (test modules) utils/ __init__.py blasttofasta.py 但例外情况是:

Traceback (most recent call last):
  File "utils/blasttofasta.py", line 5, in <module>
    import mapp.core.tobeimported
ImportError: No module named mapp.core.analyzers
回溯(最近一次呼叫最后一次):
文件“utils/blasttofasta.py”,第5行,在
导入mapp.core.tobeimported
ImportError:没有名为mapp.core.analyzers的模块
如何导入tobeimported模块?我从top目录(main.py所在的目录)运行blasttofasta.py

编辑:也许更好的问题是:如何将mapp包获取到sys.path?因为脚本文件只看到它自己的目录,而看不到包目录


谢谢

按照绝对结构导入

在tobeimport.py中导入blasttofasta.py的步骤

托贝港内容物
你的结构很好。

需要发生两件事:

  • 您的
    映射
    目录需要一个
    初始化.py
    文件
您可以简单地(天真地)这样做:

  • /path/to/map
    需要位于
    sys.path

请阅读:了解更多详细信息。

如果我想包含blasttofasta.py或同时作为脚本运行它,最重要的是在sys.path中有包含mapp包的目录

这对我很有效:

在导入mapp(或此包中的其他模块)之前,我在blasttofasta.py中写道:

import os
os.sys.path.append(os.path.dirname(os.path.realpath(__file__))+ '/../../')

这个append mapp包路径,我可以作为脚本运行它。另一方面,它包含在另一个包中没有问题。

如果我从包含mapp包的目录运行blasttofasta.py,那么它就在sys.path中,不是吗?不是。默认情况下,Python只将当前工作目录添加到
sys.path
和任何已安装的包中。请阅读我发布的链接。我已经读过了。如果我让python显示cwd(通过os.getcwd()),它将显示包含mapp包的目录。不是吗?你需要提高一级
os.getcwd()
应返回包含
main.py
的路径,以便从映射导入核心
工作。再次阅读文档!好啊getcwd()返回包含main.py和mapp包/目录的目录。它与level.python-m mapp.utils.test相同
from myapp.utils import blasttofasta
$ touch /path/to/map/__init__.py
import os
os.sys.path.append(os.path.dirname(os.path.realpath(__file__))+ '/../../')