[英]relative imports in python for i don't know how many times
I have seen these sites:我看过这些网站:
python relative import example code does not work python 相对导入示例代码不起作用
Relative imports for the billionth time 十亿次相对进口
https://peps.python.org/pep-0328/ https://peps.python.org/pep-0328/
Python packages: relative imports Python 包:相对进口
Relative imports in Python Python中的相对进口
and loads more that I did not show, but they (The answers/The code) just don't work for some reason to relatively import other Python 'modules'.并加载更多我没有显示的内容,但它们(答案/代码)由于某种原因无法相对导入其他 Python“模块”。 And for always, I have this forever-recurring error:
ImportError: attempted relative import with no known parent package
.永远,我有这个永远重复出现的错误:
ImportError: attempted relative import with no known parent package
。
My directory structure looks like this:我的目录结构如下所示:
program/
|_ main.py
|_ lib/
|_ __init__.py
|_ module1.py
|_ module2.py
|_ module3.py
In main.py:在 main.py 中:
from .lib.module1 import do_this
print('Imported')
In module1.py:在 module1.py 中:
def do_this():
print('I did it')
I'm using Linux to do this, but it just doesn't work!!!我正在使用 Linux 来执行此操作,但它不起作用!!!
EDIT:编辑:
I don't want to have to do python3 -m <module> main.py
And apparently it still does not work without the dot.我不想做
python3 -m <module> main.py
而且显然没有点它仍然无法工作。
I've had similar issues and I've created an experimental new import library ultraimport that allows to do file system based imports to solve your issue.我遇到过类似的问题,我创建了一个实验性的新导入库ultraimport ,它允许进行基于文件系统的导入来解决您的问题。
In your main.py you would then write:然后在你的 main.py 中你会写:
import ultraimport
do_this = ultraimport('__dir__/lib/module1.py', 'do_this')
print('Imported')
and it will always work, no matter how you run your code.无论您如何运行代码,它都会始终有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.