Reputation: 9165
I wonder why my simple example building a class is not properly working:
The tree-structure looks like the following
class_project/
├── class_project
│ ├── __init__.py
│ └── classtheclass.py
└── tests
├── __init__.py
└── test.py
classtheclass.py looks like this:
class ClassTheClass(object):
def __init__(self):
print "yeees"
test.py looks like this:
from class_project.classtheclass import ClassTheClass
i = ClassTheClass()
While init.py are empty
so if i execute on the shell
python test.py
its giving me
Traceback (most recent call last): File "test.py", line 1, in from class_project.classtheclass import ClassTheClass ImportError: No module named class_project.classtheclass
Whats wrong with that. In Pycharm this even works...!
Upvotes: 0
Views: 92
Reputation: 936
Your file tree structure is wrong, if you are not exporting PYTHONPATH with the new lib path, you have to put the test.py
as below structure to make the test.py to access classtheclass from class_project.
class_project/
├── class_project
│ ├── classtheclass.py
│ └── __init__.py
└── test.py
Upvotes: 1
Reputation: 164
Python search imported module as follow, for example import foo
built-in
module, If foo
isn't a built-in
module, go to nextsys.path
, sys.path
will include: current directory, PYTHONPATH
and installation dependent path. If foo
is in sys.path
, it will be imported. Otherwise, it will be ImportError
.Here, you can execute at project parent directory or explicit add /path/to/project
to sys.path
.
Upvotes: 0
Reputation: 55207
When you run python test.py
, the interpreter will look for Python code in standard library locations (e.g. /usr/local/lib/python2.7/site-packages
and friends) and in the tests
folder where you invoked the interpreter (this set of locations is known as the "Python Path", and you can view it with: import sys; print sys.path
).
None of those locations include class_project.classtheclass
.
There are a variety of ways to solve this problem.
You can set the PYTHONPATH
environment variable to include class_project
:
export PYTHONPATH="/path/to/class_project:$PYTHONPATH" # Note: this has to be the top-level class_project directory, you have two with this name here.
python test.py # This will now work
You could probably also use a relative import, but I'd argue that's working around the problem not solving the problem.
Upvotes: 1