Don't understand module search path...

Chris Mellon arkanes at gmail.com
Thu Oct 4 14:48:11 EDT 2007


On 10/4/07, mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
<mhearne808 at gmail.com> wrote:
> 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?

No. foo will be searched for modules, but foo itself won't be found
(because it's looking *inside* foo). You want "test" to be on sys.path
for this to work.

>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...
>

The directory that the executing script is in is implicitly on
sys.path, so when you do this you place "test" in sys.path, and foo is
found.



More information about the Python-list mailing list