从另一个目录导入 python 个文件

import python files from another dierctory

我已经尝试了太多 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 #文件夹1

from . import file1
from . import file2

__init__.py #文件夹2

from . import another_file1
from . import another_file2

__init__.py #项目

from . import folder1
from . import folder2

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

No module named file1.

No module named file2.

SystemError: Parent module '' not loaded, cannot perform relative import

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

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

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

P.S。使用 Python 3.5

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

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

一切就绪。