简体   繁体   English

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

[英]How to import package modules from in-package “main” module

My package structure is: 我的包裹结构是:

main.py
mapp/
   __init__.py
   core/
     __init__.py
     tobeimported.py
   test/
     __init__.py
     (test modules)
   utils/
     __init__.py
     blasttofasta.py

The file blasttofasta.py is executed as script. 文件blasttofasta.py作为脚本执行。

blasttofasta.py looks like: blasttofasta.py看起来像:

import mapp.core.tobeimported

def somefunc():
   pass


if __name__ == '__main__':
  pass

But Exception occurs: 但是发生异常:

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

How to import tobeimported module? 如何导入tobeimported模块? I run the blasttofasta.py from top directory (where main.py is) 我从顶层目录(其中main.py在)运行blasttofasta.py

EDIT: Maybe better question is: How to get mapp package to the sys.path? 编辑:也许更好的问题是:如何获取mapp包到sys.path? Because script file only see its own directory but not the package directory. 因为脚本文件只能看到其自己的目录,而不能看到包目录。

Thank you 谢谢

If I want to including blasttofasta.py or run it as script simultaneously mos important is to have directory containing mapp package in sys.path. 如果要包含blasttofasta.py或同时作为脚本运行mos,最重要的是在sys.path中具有包含mapp软件包的目录。

This worked for me: 这为我工作:

Before importing mapp (or other module from this package) I wrote into blasttofasta.py: 在导入mapp(或此软件包中的其他模块)之前,我写了一份blasttofasta.py:

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

This append mapp package path and I can run it as script. 这个附加的mapp包路径,我可以将其作为脚本运行。 On the other side is no problem with is included in another package. 另一方面,另一个程序包中没有问题。

Follow the absolute structure to import. 遵循绝对结构进行导入。

To import blasttofasta.py in tobeimport.py 要将blasttofasta.py导入到tobeimport.py中

ToBeimport contents 导入内容

from myapp.utils import blasttofasta

Your structure is good. 你的结构很好。

Two things need to happen: 需要发生两件事:

  • Your map directory needs a __init__.py file. 您的map目录需要一个__init__.py文件。

You can simply do this ( naively ): 您可以( 天真的 )简单地做到这一点:

$ touch /path/to/map/__init__.py
  • /path/to/map needs to be in sys.path /path/to/map必须在sys.path

Please read: http://docs.python.org/2/tutorial/modules.html for more details. 请阅读: http : //docs.python.org/2/tutorial/modules.html了解更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM