[英]importing sibling file in a module in python3
my python project has this directory structure 我的python项目有这个目录结构
├── main.py
└── util
├── color.py
├── __init__.py
└── student.py
main.py
is : main.py
是:
from util.student import fun
fun("calling fun from main")
color.py
is : color.py
是:
def color_fun(a):
print(a)
student.py
is : student.py
是:
from color import color_fun
def fun(var):
color_fun(var)
if __name__ == "__main__":
fun("calling fun from student")
__init__.py
is empty __init__.py
为空
when I try to run python3 student.py
it works as expected. 当我尝试运行python3 student.py
它按预期工作。 but when I try to run python3 main.py
it doesn't work as expected, while it works fine in python2. 但是当我尝试运行python3 main.py
它没有按预期工作,而它在python2中工作正常。
I want to run python3 student.py
as well as python3 main.py
how could I achieve this? 我想运行python3 student.py
以及python3 main.py
我怎么能实现这个?
All you need to do is this slight modification in your student.py
您需要做的就是在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 Python3的PYTHONPATH
导致了这个问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.