Reputation: 792
I have been confusing Python 3's difference from Python 2 about import.
If I have such a directory like this...
module_test/ ->
a/hello.py
lib/mad.py
And I want to import hello module from lib/mad.py
So I wrote code like this..
lib/mad.py
import a.hello
And I call python lib/mad.py ,but it happend ImportError.
I don't know why it happen like this.
Do you have any idea? I want to solve this question.
Sample repository is https://github.com/okamurayasuyuki/module_test/tree/master/lib . ##Thanks in advance.
Upvotes: 1
Views: 5091
Reputation: 20816
Your problem is that by running mad.py
from the module_test
directory, you guessed that Python would use your current directory as base for finding module b
. To prove that it doesn't work, do the following:
Edit your mad.py
script and add the following to the beggining of the script:
import sys
print(sys.path)
exit()
This will just print the search path Python uses to find modules you try to import and then exit.
Open the terminal, go to folder /module_test
and run the following:
> python lib/mad.py
Now you should see the path dumped to the terminal. Note that the first entry in the list is the folder 'module_test/lib' not 'module_test' as you would have thought.
So, how do you solve the problem?
Simple: you just have to tell Python the correct directory it should be using to look for your modules. To do that, you must set the PYTHONPATH enviroment variable:
> export PYTHONPATH=$PYTHONPATH:/path/to/module_test
Now if you try to run your script, it should import a.hello
as expected!
PS: You should read the official Python tutorial, specially chapter 6 which explains the concept of modules and packages:
http://docs.python.org/3/tutorial/modules.html
That should give you a basic understading and help you solve your problem.
Upvotes: 2