繁体   English   中英

从另一个目录导入类 - Python

[英]Importing classes from another directory - Python

当前位置:ProjectName / src

类位置:ProjectName / Factory Modules / Factory Classes

试试1:

from FactoryClass1 import FactoryClass1

试试2:

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

但是我继续得到'ImportError:没有名为PointSet的模块'。

如何编写import语句以便能够使用类中的函数?

您可以尝试以下方法:

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()

请参阅: Python 3.2+中execfile的替代方案?


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

PYTHONPATH=$PWD/FooDir ./foo.py

对于替代解决方案,请检查: 如何导入其他Python文件?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM