![](/img/trans.png)
[英]Python - How do you import a module into a subfolder from another folder?
[英]How do you import a module that imports another module in a subfolder?
所以这是我的文件夹结构:
root
module_a
hello.py
submodule_a
hi.py
module_b
howdy.py
hello.py
调用hi.py
中的一个方法。 howdy.py
调用hello.py
中的一个方法
这是每个文件的内容:
hi.py
def myhi(hi):
print("myhi " + hi)
hello.py
from submodule_a.hi import myhi
def myhello(hello):
myhi("myhello " + hello)
howdy.py
from module_a.hello import myhello
def myhowdy(howdy):
myhello("myhowdy " + howdy)
所以第一个问题是howdy.py
找不到module_a
,所以我在howdy.py
中做了sys.path.append(".")
。
但是现在新的问题是,从howdy.py
中,它无法从hello.py
中找到submodule_a
。
你如何解决这个问题? 是否可以完全不编辑hello.py
来解决它?
我试过弄乱__init__.py
但我找不到任何可以解决第二个问题的东西。
在module_a
和module_b
和submodule_a
中创建一个__init__.py
文件,然后在另一个目录中导入要使用的函数,如下所示:
模块_a/__init__.py
from hello import myhello
from submodule_a import myhi
module_a/submodule_a/__init__.py
from hi import myhi
模块_b/__init__.py
from howdy import myhowdy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.