Skip to main content
 首页 » 编程设计

python之如何从包内 "main"模块导入包模块

2025年05月04日9bluestorm

我的包结构是:

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 looks like:

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 所在的目录)运行 blastofasta.py

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

谢谢

请您参考如下方法:

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

这对我有用:

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

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

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