1

I am trying to import a module foo.foo within the script 'main/main.py'.

Here is the directory structure:

chenjiasheng@ubuntu:~/code/test$ pwd
/home/chenjiasheng/code/test
chenjiasheng@ubuntu:~/code/test$ find
.
./foo
./foo/foo.py
./main
./main/main.py

And the content of the two files is:

chenjiasheng@ubuntu:~/code/test$ cat ./foo/foo.py 
pass
chenjiasheng@ubuntu:~/code/test$ cat ./main/main.py 
import sys
sys.path.append('/home/chenjiasheng/code/test')
print(sys.path)
import foo.foo

'main/main.py' is supposed to append 'foo/' to its module search path. But running it with python2 gives ImportError:

chenjiasheng@ubuntu:~/code/test$ python2 main/main.py 
['/home/chenjiasheng/code/test/main', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linues', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/home/chenjiasheng/code/test']
Traceback (most recent call last):
  File "main/main.py", line 4, in <module>
    import foo.foo
ImportError: No module named foo.foo

In contrast, running it with python3 is OK:

chenjiasheng@ubuntu:~/code/test$ python3 main/main.py 
['/home/chenjiasheng/code/test/main', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linu
chenjiasheng@ubuntu:~/code/test$

According to the manual, https://docs.python.org/2/tutorial/modules.html#the-module-search-path, the sys.path variable should work for python2 as well as for python3.

So what did I do wrong?

1 Answer 1

4

Your foo package doesn't have an __init__.py file to identify it as a package. Under Python 3 this can still be imported as part of a namespace package, but this feature isn't backported to Python 2. Adding an empty __init__.py should mean you can also import that package in Python 2.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I should have been more careful when reading the tutorial as a beginner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.