Marto Marto - 1 year ago 81
Python Question

Python does not recognize a module which is set by PYTHONPATH

I've searched for some time to find a solution to this problem but have come up dry. I'm hoping I can find some help here. As the title suggests, python is not recognizing a module that has been set in my


I'm currently working on a project that has the following overall structure:

├── util
│   └──
└── project
└── app

This is executed in python 3.5 via a virtual environment called
. I use a Mac running El Capitan.

script calls the
using the following import statement:

from util.logging_utility import method

When executing, I receive this error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'util.logging_utility'

I am running this in the terminal from the
level of the directory. I'm using the following command to call the script:

PYTHONPATH=$HOME/base VIRTUAL_ENV=$HOME/.virtualenvs/venv_1 PATH=$VIRTUAL_ENV/bin:$PATH $HOME/.virtualenvs/venv_1/bin/python -- project/app/

Now, I've tried to debug this by printing out my
as well as
. In both cases, the
directory appears in the path. So why on earth am I receiving this error?

I've also tried to update the import statement to
from base.util.logging_utility import method
which gives me the following error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'base'

Any idea why this is happening and how I can correct this?



Thanks to Billy and Moinuddin Quadri whose suggestions solved the issue. For some reason I still needed to add the
files. Even though python 3.3+ supports implicit imports, looks like it was still needed. This solved the problem.

Answer Source

You might not be having the path to package in your PYTHONPATH. In order to add that, do:

 import sys

Since from Python 3.3, you do not need the

For the older version, the other possible reason is missing If you do not have a file present in the directory, you can not import files of that directory.

As is mentioned in the Packages Document:

The files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download