简体   繁体   English

从包中导入并运行子包

[英]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 启动)

main.py主文件

from package.test import print_hello

print_hello()

package/test.py包/test.py

from subpackage.hello import return_hello

def print_hello():
    print(return_hello())

package/subpackage/hello.py包/子包/hello.py

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 ?我究竟做错了什么 ?


edit : I managed to use an absolute path as recommended but now when I try to put everything in a subfolder pylint is not able to import.编辑:我设法按照建议使用了绝对路径,但是现在当我尝试将所有内容都放在子文件夹中时,pylint 无法导入。

└── 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.

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