【问题标题】:ModuleNotFoundError when importing local module from sub folder in Python [duplicate]从 Python 中的子文件夹导入本地模块时出现 ModuleNotFoundError [重复]
【发布时间】:2021-10-23 20:24:06
【问题描述】:

文件组织

./helper.py
./caller1.py
./sub_folder/caller2.py

caller1.py导入helper.py就可以了。

caller1.py

from helper import hello
if __name__ == '__main__':
    hello()

但是当使用 完全相同的代码./sub_folder/caller2.py 导入时,我得到了错误...

ModuleNotFoundError: No module named 'helper'

由于项目很大,我想将文件组织到子文件夹中。

【问题讨论】:

    标签: python python-import subdirectory project-organization


    【解决方案1】:

    作为解决方案, 您可以使用sys 模块在系统中添加该文件的路径,然后您可以导入该特定文件。

    就像你的情况

    caller2.py

    import sys
    sys.path.insert(0, "C:/Users/D_Gamer/Desktop/pyProject/helperDir")
    # You need to provide path to the directory in which you have a helper file so basically I have "helper.py" file in "helperDir" Folder
    
    from helper import hello
    
    if __name__ == '__main__':
        hello()
    

    还有其他方法可以达到同样的效果,但现在你可以坚持下去 有关更多信息,请查看Github上的此参考

    【讨论】:

    • 行了!但是如何插入父目录? sys.path.insert(0, '..') 似乎不起作用。
    • 是的,您可以使用 os 模块获取当前工作目录,然后也可以从中获取父目录python import os # get current directory path = os.getcwd() print("Current Directory", path) print() # parent directory parent = os.path.dirname(path) print("Parent directory", parent)
    【解决方案2】:

    您必须了解 Python 在使用 import 时如何找到模块和包。

    当您执行 python 代码时,该文件所在的文件夹将被添加到 PYTHONPATH 中,这是 python 将在其中查找您的包和模块的所有位置的列表。

    当你调用 caller1.py 时,它可以工作,因为 helper.py 在同一个文件夹中,但它不适用于 caller2.py,因为 python 没有在同一个文件夹中找到它,也没有在 PYTHONPATH 中的其他路径中找到它。

    您有三个选择:

    • 从与助手位于同一文件夹中的脚本调用 caller2.py
    • 在 PYTHONPATH 中添加包含 helper.py 的文件夹(不推荐)
    • 将您的代码制作成一个您可以pip install -e 的包,这样python 将能够找到您的模块,因为它们将安装在您的python 环境的站点包中(最复杂但最干净的解决方案)

    【讨论】:

    • 感谢您的解释。为简单起见,我会选择第一个选项。加上@D_Gamer sys path hack,我想我明白了。
    猜你喜欢
    • 2021-12-05
    • 2022-10-16
    • 2019-07-03
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    相关资源
    最近更新 更多