【问题标题】:How to import package modules from in-package "main" module如何从包内“主”模块导入包模块
【发布时间】:2013-12-28 03:07:06
【问题描述】:

我的包结构是:

主文件 地图/ __init__.py 核/ __init__.py tobeimported.py 测试/ __init__.py (测试模块) 实用程序/ __init__.py blasttofasta.py

文件blasttofasta.py作为脚本执行。

blasttofasta.py 看起来像:

import mapp.core.tobeimported

def somefunc():
   pass


if __name__ == '__main__':
  pass

但出现异常:

Traceback (most recent call last):
  File "utils/blasttofasta.py", line 5, in <module>
    import mapp.core.tobeimported
ImportError: No module named mapp.core.analyzers

如何导入tobeimported模块?我从顶层目录(main.py 所在的位置)运行blasttofasta.py

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

谢谢

【问题讨论】:

  • python -m mapp.utils.test

标签: python


【解决方案1】:

按照绝对结构导入。

在tobeimport.py中导入blasttofasta.py

待导入内容

from myapp.utils import blasttofasta

你的结构很好。

【讨论】:

    【解决方案2】:

    需要做两件事:

    • 您的map 目录需要一个__init__.py 文件。

    你可以简单地这样做(天真):

    $ touch /path/to/map/__init__.py
    
    • /path/to/map 需要在 sys.path

    更多详情请阅读:http://docs.python.org/2/tutorial/modules.html。

    【讨论】:

    • 如果我从包含 mapp 包的目录中运行 blasttofasta.py,那么它在 sys.path 中,不是吗?
    • 没有。默认情况下,Python 仅将 当前工作目录 添加到 sys.path 和任何已安装的包。请阅读我发布的链接。
    • 我读过了。如果我让 python 显示 cwd(通过 os.getcwd()),它会显示包含 mapp 包的目录。不对吗?
    • 您需要提升一级。 os.getcwd() 应该返回包含 main.py 的路径,以便 from map import core 工作。再次阅读文档!
    • OK .. os.getcwd() 返回包含 main.py 和 mapp 包/目录的目录。是同一级别。
    【解决方案3】:

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

    这对我有用:

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

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

    此附加 mapp 包路径,我可以将其作为脚本运行。另一边是没有问题的,包含在另一个包中。

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 2017-02-25
      • 2020-08-27
      • 1970-01-01
      • 2019-05-26
      • 2013-07-29
      • 2018-08-16
      • 1970-01-01
      • 2012-12-24
      相关资源
      最近更新 更多