简体   繁体   English

python 中的相对进口,我不知道有多少次

[英]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.

相关问题 为什么相对导入在Python 3中不起作用? - Why don't relative imports work in Python 3? Python Flask中的相对导入似乎不起作用 - Relative imports in Python Flask don't seem to work 使用 Python 在 Maya 中,相对模块导入不起作用 - Relative Module imports don't work in Maya using Python 如果我不知道列表中有多少个值,则使用 SQL 语句 - SQL statement if I don't know how many values in list 如果我不知道要添加多少变量,如何向类添加更多变量 (python) - How do I add more variables to class if I don't know how many I would add (python) Python:类型错误,但我不知道要更改什么! 对 Smtplib 了解很多的人的问题 - Python: Type Error, but I don't know what to change! Question for Someone who know many about Smtplib Python函数-不知道需要多少个参数时如何动态调用函数? - Python Functions - how can I dynamically call a function when I don't know how many arguments it expects? 我有一个 python TypeError,我不知道如何修复它 - I have a python TypeError and I don't know how to fix it 我不知道如何在 python gurobipy 中表达求和 - i don't know how to express summation in python gurobipy 我不知道如何在 python 范围内输入日期 - I don't know how to input a date within a range in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM