[英]Import packages with dependency of local modules in python
I am trying to understand how to import a module from a package from another folder in python, considering that this module imports a local module.我试图了解如何从 python 中的另一个文件夹从 package 导入模块,考虑到该模块导入本地模块。
Say I have the following structure:假设我有以下结构:
C:.
│ e.py
│
└───src
├───a
│ │ b.py
│ │ context.py
│ │ __init__.py
│ │
│ └───__pycache__
│ context.cpython-38.pyc
│
└───c
│ d.py
│ f.py
│ __init__.py
│
└───__pycache__
d.cpython-38.pyc
f.cpython-38.pyc
__init__.cpython-38.pyc
Say I want to use the method (f.print_loca()) in b.py, currently running b prompts me:说我要使用b.py中的方法(f.print_loca()),当前运行的b提示我:
Actual:
Traceback (most recent call last):
File "..\src\a\b.py", line 2, in <module>
from b import f
File "..\src\b\f.py", line 1, in <module>
import d
ModuleNotFoundError: No module named 'd'
Expected: d->f
How could I fix this import error?我该如何解决这个导入错误?
Below is what I have以下是我所拥有的
b.py b.py
from context import c
from c import f
f.print_loca()
context.py上下文.py
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import c
d.py d.py
def print_mes():
print("d")
f.py文件
import d
def print_loca():
print(d.print_mes()+"->"+"f")
Thank you谢谢
Try using "."尝试使用“。” before start so:
在开始之前:
if you were to import d into bi would do something like:如果您要将 d 导入 bi 会执行以下操作:
from .src.c.d import *
# or from .src.c import d
# or import .src.c.d
Also it's better practice to only sys reference project root dir i think.此外,我认为仅 sys 参考项目根目录是更好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.