[英]Import and run a subpackage from within a package
I'm looking for a way to import a subpackage from within a package in Python 3. Consider the following structure :我正在寻找一种从 Python 3 中的包中导入子包的方法。考虑以下结构:
├── main.py
└── package
├── subpackage
│ └── hello.py
└── test.py
What I would like to do is use a function that inside hello.py from within test.py (which is launched by main.py)我想做的是在 test.py 中使用 hello.py 中的函数(由 main.py 启动)
from package.test import print_hello
print_hello()
from subpackage.hello import return_hello
def print_hello():
print(return_hello())
def return_hello():
return "Hello"
But I'm getting the following error :但我收到以下错误:
Traceback (most recent call last):
File ".\main.py", line 1, in <module>
from package.test import print_hello
File "D:\Python\python-learning\test\package\test.py", line 1, in <module>
from subpackage.hello import return_hello
ModuleNotFoundError: No module named 'subpackage'
I tried putting a .
我试着把
.
in test.py
and it worked, but my linter does not like it.在
test.py
它起作用了,但我的 linter 不喜欢它。
What am I doing wrong ?我究竟做错了什么 ?
└── src
├── main.py
└── package
├── subpackage
│ └── hello.py
└── test.py
Just use只需使用
from .subpackage.hello import return_hello
instead of代替
from subpackage.hello import return_hello
in your test.py file and read this guide for better understanding how imports works in python.在您的 test.py 文件中并阅读本指南以更好地理解导入在 Python 中的工作原理。
You can see fixed result here : https://repl.it/@ent1c3d/SoupySadUnderstanding您可以在此处查看固定结果: https : //repl.it/@ent1c3d/SoupySadUnderstanding
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.