Python 找不到在另一个模块中导入的模块
Python can't find a module, that is imported in another module
我有一个这样的项目结构:
│ main.py
│
├───equations
│ resolving.py
│ resolving_methods.py
│ __init__.py
│
└───func
│ converter.py
│ __init__.py
│
└───templates
func_template.py
我试图从 func.converter 导入到 main.py class 并从 equations.resolving_methods
导入所有 classes
from func.converter import func_converter
from equations.resolving_methods import *
在这个文件中(转换器和 resolving_methods)我有这行代码:
/converter.py
with open('templates/new_func.py', 'w', encoding='utf-8') as new_f:
from templates.new_func import my_func
/resolving_methods:
from resolving import resolving
和python给出以下错误:
ImportError: No module named 'resolving'
但是,当我尝试单独 运行 这些文件时,代码运行没有任何错误
您正在使用绝对导入。绝对导入只找到 顶级模块 ,而你试图导入嵌套在包中的名称。
您需要指定完整的包路径,或者使用包相关引用,使用 .
:
# absolute reference with package
from equations.resolving import resolving
# package relative import
from .resolving import resolving
请参阅 Python 教程的 Intra-package References section。
您的 converter.py
模块存在尝试打开具有相对路径的文件的额外问题。路径 'templates/new_func.py'
将根据 当前工作目录 的任何位置进行解析,它可以位于计算机上的任何位置。使用绝对路径,基于模块__file__
参数:
import os.path
HERE = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(HERE, 'new_func.py'), 'w', encoding='utf-8') as new_f:
我有一个这样的项目结构:
│ main.py
│
├───equations
│ resolving.py
│ resolving_methods.py
│ __init__.py
│
└───func
│ converter.py
│ __init__.py
│
└───templates
func_template.py
我试图从 func.converter 导入到 main.py class 并从 equations.resolving_methods
导入所有 classesfrom func.converter import func_converter
from equations.resolving_methods import *
在这个文件中(转换器和 resolving_methods)我有这行代码:
/converter.py
with open('templates/new_func.py', 'w', encoding='utf-8') as new_f:
from templates.new_func import my_func
/resolving_methods:
from resolving import resolving
和python给出以下错误:
ImportError: No module named 'resolving'
但是,当我尝试单独 运行 这些文件时,代码运行没有任何错误
您正在使用绝对导入。绝对导入只找到 顶级模块 ,而你试图导入嵌套在包中的名称。
您需要指定完整的包路径,或者使用包相关引用,使用 .
:
# absolute reference with package
from equations.resolving import resolving
# package relative import
from .resolving import resolving
请参阅 Python 教程的 Intra-package References section。
您的 converter.py
模块存在尝试打开具有相对路径的文件的额外问题。路径 'templates/new_func.py'
将根据 当前工作目录 的任何位置进行解析,它可以位于计算机上的任何位置。使用绝对路径,基于模块__file__
参数:
import os.path
HERE = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(HERE, 'new_func.py'), 'w', encoding='utf-8') as new_f: