【问题标题】:import python files from another dierctory从另一个目录导入python文件
【发布时间】:2017-09-12 23:39:26
【问题描述】:

我尝试了太多在 SO 上提供的解决方案,但无法完成这项工作。

这是目录结构。

|project
|------->folder1
|-------------->file1.py   #file1.py contains class File1
|-------------->file2.py   #file2.py contains class File2
|------->folder2
|-------------->another_file1.py   #another_file1.py contains class SomeClass1
|-------------->another_file2.py   #another_file2.py contains class SomeClass2
|------->Runner
|-------------->logic.py

我需要在logic.py 中创建所有类的实例 我在所有文件夹中创建了__init__.py,并在主项目中创建了一个。

__init__.py #folder1

from . import file1
from . import file2

__init__.py #folder2

from . import another_file1
from . import another_file2

__init__.py #项目

from . import folder1
from . import folder2

我无法导入Runner 中的任何内容。 我收到以下错误。

没有名为 file1 的模块。

没有名为 file2 的模块。

系统错误:父模块''未加载,无法执行相对导入

但是我可以通过这个调整让它工作。

import sys
sys.path.append('../')

Runner 目录内的我的文件中。但我不想在我的每个文件中都这样做。

附:使用 Python 3.5

【问题讨论】:

  • 如果你使用相对导入,它应该是 from ..folder1 import blahfrom ...project import blah
  • @DmitryPolonskiy: 使用..... 给出相同的错误。 SystemError: Parent module '' not loaded, cannot perform relative import
  • 我不认为没有使用该调整或相对路径来处理此问题的好方法。当您使用流行的框架、工具、库时,这些项目中的大多数都将 runner 放在顶级文件夹中。因此,为了获得最佳实践,您应该将 runner 放在顶级文件夹中。
  • @KirChou:是的,这似乎是目前唯一的选择,但我很好奇如果[将来]我创建一个新文件夹Commons,它可以包含多个类。如果然后我尝试从Commons 加载到folder1 等,也会出现同样的问题。希望你明白我的意思。
  • @Mubin 另一种方式,不推荐将您尝试从中导入的那些文件的路径添加到您的路径中,您似乎试图在您的代码中这样做,但所有您添加的是一个斜线。

标签: python python-3.x python-module


【解决方案1】:

遇到相同问题的任何人都可以这样做。

1) 创建新项目,例如:StreamingApplication。

|root --StreamingApplication
|-------> utils
|-------------->helper.py
|-------------->storage_handler.py
|------->config
|-------------->config.py
|-------------->hook.py
|------->app
|-------------->application.py

所以,如果你想将文件夹标记为python包,你也可以创建__init__.py文件。

将项目根路径添加到PYTHONPATH系统变量。

~/.bashrc 或 /etc/profile

export PYTHONPATH=/path/to/StreamingApplication

带有source ~/.bashrcsource /etc/profile 的源文件

然后在application.py 你可以做这样的事情。

from utils.helper import write_file #write_file is function.
from utils.storage_handler import StorageHandler # StorageHandler is class
import config as conf

class App:
    def __init__(self):
        self.executors = conf.executors  # access  executors variable from config

一切就绪。

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2023-02-02
    • 2021-09-23
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 2020-03-04
    • 2018-04-24
    相关资源
    最近更新 更多