简体   繁体   中英

importing sibling file in a module in python3

my python project has this directory structure

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

main.py is :

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

color.py is :

def color_fun(a):
    print(a)

student.py is :

from color import color_fun

def fun(var):
    color_fun(var)

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

__init__.py is empty

when I try to run python3 student.py it works as expected. but when I try to run python3 main.py it doesn't work as expected, while it works fine in python2.

I want to run python3 student.py as well as python3 main.py how could I achieve this?

All you need to do is this slight modification in your 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

The PYTHONPATH for Python3 is causing the problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM