从另一个目录导入 类 - Python

Importing classes from another directory - Python

当前位置:ProjectName/src

类 位置:ProjectName/Factory Modules/Factory 类

尝试 1:

from FactoryClass1 import FactoryClass1

尝试 2:

import sys
sys.path.append(path_to_classes_folder)
from FactoryClass1 import FactoryClass1

然而我不断得到 'ImportError: No module named PointSet'。

导入语句应该怎么写才能使用类中的函数?

您可以尝试类似的方法:

import os.path, sys
# Add current dir to search path.
sys.path.insert(0, "dir_or_path")
# Add module from the current directory.
sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.realpath(__file__))) + "/dir")

这会将您的目录添加到 Python 搜索路径。然后你可以像往常一样导入。

要查看添加了哪些路径,请检查:

import sys
from pprint import pprint
pprint(sys.path)

如果仍然不起作用,请确保您的模块是有效的 Python 模块(目录中应包含 __init__.py 文件)。如果不是,则创建一个空的。


或者只加载 类 内联,在 Python 3 中你可以使用 exec(),例如:

exec(open(filename).read())

在 Python 2: execfile().

参见:Alternative to execfile in Python 3.2+?


如果您从命令行 运行 您的脚本,您还可以通过定义 PYTHONPATH 变量来指定 Python 路径,因此 Python 可以查找模块在提供的目录中,例如

PYTHONPATH=$PWD/FooDir ./foo.py

对于替代解决方案检查:How to import other Python files?