Don't understand module search path...

mhearne808[insert-at-sign-here]gmail[insert-dot-here]com mhearne808 at gmail.com
Thu Oct 4 20:32:38 CEST 2007


I think I don't understand how the module search path works...

Let's say I have a folders called 'test'.  Underneath it, I create two
more folders called 'foo' and 'bar'.

In 'foo', I create an empty '__init__.py' file, indicating that this
folder is a package 'foo'.  I then create a simple python script
'foo.py' consisting of the following code:

----------------------------
#!/usr/bin/python

def printhello():
    print 'Hello world!'
----------------------------

Then in test/bar, I create 'bar.py' consisting of the following code:
----------------------------
#!/usr/bin/python
import sys
import os
(curpath,thisdir) = os.path.split(os.getcwd())
foopath = os.path.join(curpath,'foo')
sys.path.append(foopath)
print sys.path
os.chdir(os.path.join(os.getcwd(),'..'))
print os.getcwd()
from foo.foo import printhello
----------------------------

When I try to run bar.py, I get the following:

----------------------------
[sys.path search path, including full path to 'foo' folder]
path/to/test
Traceback (most recent call last):
  File "/path/to/test/bar/testfoo.py", line 16, in <module>
from foo.foo import printhello
ImportError: No module named foo
----------------------------

Why?  If 'foo' is in sys.path, shouldn't it appear when I try to
import the foo module from it?  Incidentally, when I move the script
up to 'test' and modify it so that it just says:
----------------------------
#!/usr/bin/python

from foo.foo import printhello
----------------------------

I get no errors.  I don't understand the difference...

Incidentally, my platform info:
Python 2.5.1
Darwin Kernel Version 8.10.1 (Mac OS X)

Help!

--Mike




More information about the Python-list mailing list