ImportError when trying to import a custom module in Python

Note that I was looking for SO for this error, and when there were a lot of similar questions, I did not find the one that addressed this specific problem.

I am working on a Python module that looks like this:

/com /company /foo /bar 

I am editing the source file in the bar directory and trying to import classes that live in the foo directory. I tried to import files in the following ways:

 from com.company.foo import * from company.foo import * from foo import * import com.company.foo import company.foo import foo 

Each of them causes a similar error:

 ImportError: no module named com.company.foo 

I have __init__.py files in each of the directories, including the directory containing com .

Not sure what I'm doing wrong here - in advance for help!

+7
source share
2 answers

The directory containing /com must be in the Python path. There are several ways to do this:

  • At the command line every time:

     user@host :~$ PYTHONPATH=/path/to/whatever python some_file.py 
  • In the shell configuration ( .bashrc , .bash_profile , etc.):

     export PYTHONPATH=/path/to/whatever 
  • In Python code (I do not recommend this as a general practice):

     import sys sys.path.append('/path/to/whatever') 

As some of the commentators said, this is usually processed either by the container ( mod_wsgi , etc.), or by your boot / main script (which can do something like option No. 3 or can be called into the environment configured as in options # 1 or 2)

+5
source

Think from .foo import * At least 2.7 and above

0
source

All Articles