ImportError when trying to import a custom module in Python
Note that I searched SO for this error and while there were many similar questions, I didn't find one that addressed this particular issue.
I'm working on a Python module that looks like this:
/com
/company
开发者_如何学Go /foo
/bar
I'm editing a source file within the bar
directory and attempting to import classes that live in the foo
directory. I've tried importing the files 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 these produces a similar error:
ImportError: no module named com.company.foo
I have __init__.py
files in each of the directories, including the directory that contains com
.
Not sure what I'm doing wrong here - thanks in advance for you assistance!
The directory containing /com
needs to be on the Python path. There are a number of ways to do this:
At the command line, every time:
user@host:~$ PYTHONPATH=/path/to/whatever python some_file.py
In your shell configuration (
.bashrc
,.bash_profile
, etc):export PYTHONPATH=/path/to/whatever
In Python code (I don't recommend this, as general practice):
import sys sys.path.append('/path/to/whatever')
As some of the commenters said, usually this is handled either by the container (mod_wsgi
, etc) or by your bootstrap/main script (which might do something like option #3, or might be invoked in an environment set up as in options #1 or #2)
Think it's from .foo import * At least in 2.7 and up
精彩评论