【问题标题】:Why does this import give me an error message when trying to import from 2 local modules?为什么在尝试从 2 个本地模块导入时,此导入会给我一条错误消息?
【发布时间】:2021-10-03 10:22:26
【问题描述】:

我的代码结构如下:

Graph API/
│── main.py
├── helper_functions/
    ├── defines.py
    ├── insights.py

insights.py开头从defines.py导入2个函数:

from defines import getCreds, makeApiCall

然后它为此函数使用“makeApiCall”:

def getUserMedia( params ) :
    // Some code about url endpoints etc. 

    return makeApiCall( url, endpointParams, params['debug'] ) # make the api call

我想在 main.py 脚本中使用 getUserMedia 函数,所以我将其导入:

from helper_functions.insights import *

但我得到了错误:

Traceback (most recent call last):
  File "/Users/Graph_API/main.py", line 1, in <module>
    import helper_functions.insights
  File "/Users/Graph_API/helper_functions/insights.py", line 1, in <module>
    from defines import getCreds, makeApiCall
ModuleNotFoundError: No module named 'defines'

是什么导致了这个错误?当我在insights.py 中使用getUserMedia 函数时,它工作正常。我也已经尝试将 define.py 导入 main.py,但我得到了同样的错误。

我是编程新手,非常感谢您的帮助 :)

【问题讨论】:

    标签: python function recursion import python-import


    【解决方案1】:

    你应该替换

    from defines import getCreds, makeApiCall
    

    from helper_functions.defines import getCreds, makeApiCall
    

    或者

    from .defines import getCreds, makeApiCall
    

    您必须像第一个示例一样从项目目录中提供路径,或者通过添加一个点从见解文件的相对路径中提供路径。

    您也可以考虑将 init.py 添加到 helper_functions 文件夹。在这里结帐:What is __init__.py for?

    【讨论】:

    • 但是defines.py和insights.py在同一个目录下。如果我使用“from helper_functions.defines import getCreds, makeApiCall”,则导入不起作用。我尝试在 helper_functions 目录中添加一个空白的 init.py ,但这没有帮助。我认为有一些递归,因为instances.py 从defines.py 导入,main.py 从其他两个文件导入,但我不知道如何解决这个问题..
    猜你喜欢
    • 1970-01-01
    • 2013-01-01
    • 2021-12-15
    • 2021-10-11
    • 2020-10-10
    • 2022-12-07
    • 2020-06-14
    • 1970-01-01
    • 2020-11-05
    相关资源
    最近更新 更多