I found importing modules in Python complicated, so I'm doing experiments to clear it up. Here is my file structure:
PythonTest/
package/
__init__.py
test.py
Content of __init__.py
:
package = 'Variable package in __init__.py'
from package import test
Content of test.py
:
from package import package
print package
When I stay out of package
(in PythonTest
), and execute python package/test.py
, I get:
Traceback (most recent call last):
File "package/test.py", line 1, in <module>
from package import package
ImportError: No module named package
The expected output is Variable package in __init__.py
. What am I doing wrong?
However, I can get the expected output in the interactive mode:
sunqingyaos-MacBook-Air:PythonTest sunqingyao$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import package
Package in __init__.py
First Let's see how Python search for packages and modules.
sys.path
That's the search paths. Therefore, if your module/package is located in one of
sys.path
, python interpreter is able to find and import it. The doc says more:I modified
test.py
as an example.There are two cases:
As you see,
path[0]
is/Users/laike9m/Dev/Python/TestPython/package
, which is the directory containing the scripttest.py
that was used to invoke the Python interpreter.Now comes the second case, when invoked interactively, "
path[0]
is the empty string, which directs Python to search modules in the current directory first." What's the current directory?/Users/laike9m/Dev/Python/TestPython/
.(look this is the path on my machine, it's equivalent to the path toPythonTest
in your case)Now you know the answers:
Why did
python package/test.py
giveImportError: No module named package
?Because the interpreter does not "see" the package. For the interpreter to be aware of package
package
,PythonTest
has to be insys.path
, but it's not.Why did this work in interactive mode?
Because now
PythonTest
is insys.path
, so the interpreter is able to locate packagepackage
.