【问题标题】:importing sibling file in a module in python3在python3的模块中导入兄弟文件
【发布时间】:2018-09-03 21:14:15
【问题描述】:

我的python项目有这个目录结构

├── main.py
└── util
    ├── color.py
    ├── __init__.py
    └── student.py

main.py 是:

from util.student import fun
fun("calling fun from main")

color.py 是:

def color_fun(a):
    print(a)

student.py 是:

from color import color_fun

def fun(var):
    color_fun(var)

if __name__ == "__main__":
    fun("calling fun from student")

__init__.py 为空

当我尝试运行 python3 student.py 时,它按预期工作。但是当我尝试运行python3 main.py 时,它无法按预期运行,而在 python2 中运行良好。

我想同时运行 python3 student.pypython3 main.py 我怎么能做到这一点?

【问题讨论】:

    标签: python python-3.x python-import


    【解决方案1】:

    您需要做的就是在您的student.py 中稍作修改

    def fun(var):
        color_fun(var)
    
    if __name__ == "__main__":
        from color import color_fun
        fun("calling fun from student")
    else:
        from util.color import color_fun
    

    Python3 的 PYTHONPATH 导致了问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-30
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 2022-11-07
      • 2021-10-05
      相关资源
      最近更新 更多