首页 > 解决方案 > Python cant find module

问题描述

My file structure:

-launch.py
---folder
-----folder
-------__init__py
-------test.py
-------test1.py

launch.py

os.system('python3.6 -m folder.folder.test')

test.py

import test1

test1.py

def test_print():
    print("Testing testing 123")

I'm getting a module not found error because, for some reason, python is looking for modules in the directory launch.py resides in. I am able to successfully import this in test.py using import folder.folder.test1 I would just use that, but the program I am modifying already has way too many imports using import test1 (since it seems to work fine in Windows). Thank you in advanced.

标签: pythonpython-import

解决方案


import test1寻找顶级模块。如果不明确告诉 Python 查看那个包,就不能在同一个包中导入一个模块。

利用

from . import test1

或者

from folder.folder import test1

import test1仅当目录folder/folder/存在于 Python 模块搜索路径中时才有效。任何依赖工作的代码只有在直接作为当前工作目录import test1启动时才会这样做,或者当您明确添加该目录时(通过从 Python 代码更新该列表,或通过设置环境变量)。.../folder/foldersys.pathPYTHONPATH

例如,从folder.folder.test模块中,您可以使用:

import sys, os
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

使用前import test1我建议不要这样做;修复项目,而不是使用打包的命名空间正常工作。


推荐阅读