Import classes from another directory - Python

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 an import statement be written in order to be able to use functions in classes?

+4
source share
1 answer

You can 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 the Python search path. Then you can import as usual.

To find out which paths have been added, check:

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

, , Python ( __init__.py ). , .


inline, Python 3 exec(), :

exec(open(filename).read())

Python 2: execfile().

: execfile Python 3.2+?


script , Python, PYTHONPATH, Python , .

PYTHONPATH=$PWD/FooDir ./foo.py

: Python?

0

All Articles