【问题标题】:python import class from another folder's filepython 从另一个文件夹的文件中导入类
【发布时间】:2021-05-06 11:07:19
【问题描述】:

我使用的是 python 3,我的文件夹结构如下

Main_Folder
> Export
> >exportmanager.py

> Examples
>  >test.py

exportmanager.py 文件有一个 ExportManager 类,我需要在 test.py 中导入它。 到目前为止我已经尝试过

from Export.exportmanager import ExportManager
from Main_Folder.Export import exportmanager.py then from exportmanager.py import ExportManager

和其他一些。 但我一直找不到模块。

【问题讨论】:

标签: python python-3.x import


【解决方案1】:

假设你的 exportmanager.py 看起来像这样:

def fun():
    print("This is from Export Manager!")

您可以在 test.py 中编写此代码:

from pathlib import Path
from sys import path
path.append(str(Path(__file__).parents[1] /Path('Main/Export')))

import exportmanger

exportmanger.fun()

我尝试使用 Przemysław Samsel 的回答,但它会产生 ModuleNotFoundError!

【讨论】:

  • 我猜这是另一种看法,我真的不明白“/”在那里做什么。我的代码所做的只是将父目录附加到 Python 的路径。然后,如果您已经创建了所有这些 init.py 文件,正如我所指出的,Python 应该没有问题找到 exportmanager。无论如何,让我们看看OP怎么说
  • “/”在目录树中移动。我的回答是将 Main_Folder/Export 目录附加到 Python 的路径
【解决方案2】:

我想到的唯一快速而肮脏的解决方案是具有这种结构:

.
├── Examples
│   ├── __init__.py
│   └── test.py
├── Main_Folder
│   ├── Export
│   │   └── exportmanager.py
│   └── __init__.py
├── __init__.py

假设您的 exportmanager.py 如下所示:

def fun():
    print("This is from Export Manager!")

然后您将其导入您的 test.py 使用:

import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from Main_Folder.Export import exportmanager


exportmanager.fun()

我尝试使用相对导入,其他“最简单”的解决方案,它们都给出了相同的错误“ImportError:尝试使用没有已知父包的相对导入”。 因此,如果您正在寻找一个肮脏的解决方法,这可能就是它。至于为什么会有几个 init.py 文件,在这种情况下基本上是空的,我鼓励你多阅读一下(即here

玩得开心。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 2020-01-24
    • 2013-12-07
    • 2013-06-03
    相关资源
    最近更新 更多