【问题标题】:for to call a function from another file in the parent directory in Python?用于从 Python 的父目录中的另一个文件调用函数?
【发布时间】:2021-10-13 04:39:59
【问题描述】:

我已经搜索了几个线程,但没有找到很好的解决方案来解释模块/包的使用以及从另一个文件导入函数。

假设,我有一个如下的目录结构:

dir_1
 - main2.py
main.py

main.py

def print_hello():
    return "hello world!!"

现在,我如何在main2.py 中使用这个函数print_hello(),它位于dir_1 中? 如果我有一个高度嵌套的文件结构,我该如何使用它?

非常感谢任何帮助!!..

【问题讨论】:

  • 尝试在dir_1 中添加一个__init__.py 文件。添加使python将其视为模块
  • 顺便说一句,现在不需要初始化文件了。

标签: python python-3.x function file module


【解决方案1】:

一种解决方案是添加 main.py 的路径

dir_1/main2.py

import sys
sys.path.append("path/to/the/main")

from main import print_hello

#...

但我觉得导入父文件不是最佳做法。

【讨论】:

    猜你喜欢
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 2013-06-16
    • 1970-01-01
    • 2023-02-02
    • 2019-11-15
    • 1970-01-01
    相关资源
    最近更新 更多