python - 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.
解决方案
import test1
寻找顶级模块。如果不明确告诉 Python 查看那个包,就不能在同一个包中导入一个模块。
利用
from . import test1
或者
from folder.folder import test1
import test1
仅当目录folder/folder/
存在于 Python 模块搜索路径中时才有效。任何依赖工作的代码只有在直接作为当前工作目录import test1
启动时才会这样做,或者当您明确添加该目录时(通过从 Python 代码更新该列表,或通过设置环境变量)。.../folder/folder
sys.path
PYTHONPATH
例如,从folder.folder.test
模块中,您可以使用:
import sys, os
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
使用前import test1
。我建议不要这样做;修复项目,而不是使用打包的命名空间正常工作。
推荐阅读
- ssl-certificate - 邮递员测试:预计 SSL 证书到期日
- javascript - Chrome 扩展消息无法通过
- csv - Neo4j 为 CSV 导出指定字段和列名
- python - 在numpy数组中搜索
- python - 使用 Python 3.x 运行一个简单的本地 HTTP 服务器
- python - 如何分配字典中的值?(Python)
- java - 我正在尝试在树莓派上设置 Minecraft 服务器,但我在首次启动服务器时一直遇到错误
- r - 将字符分隔到新列中
- vba - 使用 VBA moodule 批量加载图像以访问数据库
- python - 如何从图片中的每个 rgb 通道获取直方图?