【问题标题】:Access function in other python file within a subfolder访问子文件夹内其他 python 文件中的函数
【发布时间】:2020-12-23 06:28:03
【问题描述】:

我正在使用各种脚本构建一个相当复杂的 python 应用程序。我计划将这些脚本分类到子文件夹中,这样我就可以从主文件中访问这些函数。例如,在名为test.py 的文件中包含一个名为main 的函数,该文件位于一个名为test 的子文件夹中。我将如何调用该函数?

我尝试过使用

from test import main

但是我收到了 ModuleNotFoundError 错误。

提前感谢您的帮助。

【问题讨论】:

  • 错过了__init__.py?它会是from test.test import main

标签: python function file


【解决方案1】:

here 所述,要从 python 中的子文件夹导入文件,请使用 '.'表示子目录。

  • 在您的示例中,导入将是

from test.test import main

  • 此类导入的一般语法如下:

from [subfolderName].[fileName] import [functionName]

  • 要从文件中导入所有函数,语法为:

import [subfolderName].[fileName]

【讨论】:

    猜你喜欢
    • 2021-07-22
    • 2014-02-09
    • 1970-01-01
    • 2021-11-08
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多