gpt4 book ai didi

python - 从包中导入并运行子包

转载 作者:太空宇宙 更新时间:2023-11-04 04:20:55 25 4
gpt4 key购买 nike

我正在寻找一种从 Python 3 中的包中导入子包的方法。考虑以下结构:

├── main.py
└── package
├── subpackage
│ └── hello.py
└── test.py

我想做的是在 test.py(由 main.py 启动)中使用 hello.py 中的函数

主.py

from package.test import print_hello

print_hello()

包/测试.py

from subpackage.hello import return_hello

def print_hello():
print(return_hello())

包/子包/hello.py

def return_hello():
return "Hello"

但我收到以下错误:

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'

我尝试在 test.py 中放置一个 . 并且它起作用了,但我的 linter 不喜欢它。

enter image description here

我做错了什么?


编辑:我设法按照推荐使用绝对路径,但现在当我尝试将所有内容放入子文件夹时,pylint 无法导入。

└── src
├── main.py
└── package
├── subpackage
│ └── hello.py
└── test.py

enter image description here

最佳答案

就用

from .subpackage.hello import return_hello

代替

from subpackage.hello import return_hello

在你的 test.py 文件中阅读 this更好地理解导入如何在 Python 中工作的指南。

你可以在这里看到固定的结果:https://repl.it/@ent1c3d/SoupySadUnderstanding

关于python - 从包中导入并运行子包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54498101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com