1

I am creating a python project with the following directory structure:

demos
   demo1.py
kernels
   rbf.py
   ___init__.py

The file rbf.py defines a class called RBF. The __init__.py file in the kernels directory contains the following line:

from .rbf import *

Now the demo1.py contains the following import:

from kernels import RBF

However, this fails with

ImportError: No module named kernels

So the demos folder does not see the kernels package directory. I am at a loss as to what to do to make this work.

2
  • Are you running the demo1.py script from the top-level directory (python demos/demo1.py)? Commented Aug 26, 2015 at 12:16
  • I ran from demos directory and the top level directory but I got the same error. Commented Aug 26, 2015 at 12:19

2 Answers 2

7

You should add the parent directory of kernels to either PYTHONPATH environment variable or directly to sys.path for Python to be able to find the package kernels .

Example of modifying sys.path in demo1.py , assuming both demo and kernels have the same parent directory -

import os, os.path
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),'..')))
from kernels import RBF

What the above does -

__file__ gets the path of the script

os.path.dirname(__file__) - gets the path of the directory containing the file.

os.path.join() - creates the path like - /path/to/demos/.. - depending on the OS.

os.path.abspath - gets the absolute path of the parent directory from /path/to/demos/..

Sign up to request clarification or add additional context in comments.

2 Comments

Ah ok... Is this very standard thing to do? I never see that in any online python projects....??? Perhaps they take care of it in the setup.py files?
Yes , there are some directories that come up automatically in sys.path , you can try printing it to see what they are . When you install a library , most of the times , they install in the correct directory such that users do not have to add it to PYTHONPATH or sys.path separately .
0

If both the demo1 and kernels are not in the same folder, you have to add the path to kernels file to the path environmental variable.

import sys
sys.path.append("/path/to/kernels") 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.