[英]Python can't find a module, that is imported in another module
I have a project structure like this:我有一个这样的项目结构:
│ main.py
│
├───equations
│ resolving.py
│ resolving_methods.py
│ __init__.py
│
└───func
│ converter.py
│ __init__.py
│
└───templates
func_template.py
I'm tried to import to main.py class from func.converter and all classes from equations.resolving_methods我试图从 func.converter 和所有类从 equations.resolving_methods 导入到 main.py 类
from func.converter import func_converter
from equations.resolving_methods import *
In this files (converter and resolving_methods) I have this lines of code:在这个文件(转换器和解决方法)中,我有这几行代码:
/converter.py /转换器.py
with open('templates/new_func.py', 'w', encoding='utf-8') as new_f:
from templates.new_func import my_func
/resolving_methods: /resolving_methods:
from resolving import resolving
And python give following error:并且python给出以下错误:
ImportError: No module named 'resolving'
But, when I try to run this files separately, code works without any errors但是,当我尝试单独运行这些文件时,代码可以正常工作而没有任何错误
You are using absolute imports.您正在使用绝对导入。 Absolute imports only find top-level modules , while you are trying to import names that are nested inside packages.当您尝试导入嵌套在包中的名称时,绝对导入只能找到顶级模块。
You'll either need to specify the full package path, or use a package-relative reference, using .
您要么需要指定完整的包路径,要么使用相对于包的引用,使用.
: :
# absolute reference with package
from equations.resolving import resolving
# package relative import
from .resolving import resolving
See the Intra-package References section of the Python tutorial.请参阅 Python 教程的包内参考部分。
Your converter.py
module has the additional issue of trying to open a file with a relative path.您的converter.py
模块还有一个额外的问题,即尝试打开具有相对路径的文件。 The path 'templates/new_func.py'
will be resolved against whatever the current working directory is going to be, which could be anywhere on the computer.路径'templates/new_func.py'
将根据当前工作目录的任何内容进行解析,该目录可以在计算机上的任何位置。 Use absolute paths, based on the module __file__
parameter:使用绝对路径,基于模块__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:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.