Importing classes from another directory - Python

匿名 (未验证) 提交于 2019-12-03 00:53:01

问题:

Current Location: ProjectName/src

Classes Location: ProjectName/Factory Modules/Factory Classes

Try 1:

from FactoryClass1 import FactoryClass1 

Try 2:

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

However I keep getting 'ImportError: No module named PointSet'.

How should the import statement be written in order to be able on using the functions in the classes?

回答1:

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. 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). If it is not, create empty one.


Alternatively to just load the classes inline, in Python 3 you may use exec(), for example:

exec(open(filename).read()) 

In Python 2: execfile().

See: Alternative to execfile in Python 3.2+?


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, e.g.

PYTHONPATH=$PWD/FooDir ./foo.py 

For alternative solutions check: How to import other Python files?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!