简体   繁体   English

从另一个目录导入类 - Python

[英]Importing classes from another directory - Python

Current Location: ProjectName/src 当前位置:ProjectName / src

Classes Location: ProjectName/Factory Modules/Factory Classes 类位置:ProjectName / Factory Modules / Factory Classes

Try 1: 试试1:

from FactoryClass1 import FactoryClass1

Try 2: 试试2:

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

However I keep getting 'ImportError: No module named PointSet'. 但是我继续得到'ImportError:没有名为PointSet的模块'。

How should the import statement be written in order to be able on using the functions in the classes? 如何编写import语句以便能够使用类中的函数?

You may try something like: 您可以尝试以下方法:

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

Which will add your directory to Python search path. 这会将您的目录添加到Python搜索路径。 Then you may import as usual. 然后你可以照常导入。

To see which paths has been added, check by: 要查看已添加的路径,请检查:

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

If still doesn't work, make sure that your module is the valid Python module (should contain __init__.py file inside the directory). 如果仍然不起作用,请确保您的模块是有效的Python模块(应该在目录中包含__init__.py文件)。 If it is not, create empty one. 如果不是,请创建空的。


Alternatively to just load the classes inline, in Python 3 you may use exec() , for example: 或者只是加载内联类,在Python 3中你可以使用exec() ,例如:

exec(open(filename).read())

In Python 2: execfile() . 在Python 2中: execfile()

See: Alternative to execfile in Python 3.2+? 请参阅: Python 3.2+中execfile的替代方案?


If you run your script from the command-line, you can also specify your Python path by defining PYTHONPATH variable, so Python can lookup for modules in the provided directories, eg 如果从命令行运行脚本,还可以通过定义PYTHONPATH变量来指定Python路径,这样Python就可以在提供的目录中查找模块,例如

PYTHONPATH=$PWD/FooDir ./foo.py

For alternative solutions check: How to import other Python files? 对于替代解决方案,请检查: 如何导入其他Python文件?

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

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