Importerror: No Module Named Package
Solution 1:
First Let's see how Python search for packages and modules. sys.path
A list of strings that specifies the search path for modules. Initialized from the environment variable
PYTHONPATH
, plus an installation-dependent default.
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:
As initialized upon program startup, the first item of this list,
path[0]
, is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input),path[0]
is the empty string, which directs Python to search modules in the current directory first.
I modified test.py
as an example.
import sys; import pprint
pprint.pprint(sys.path)
from packageimportpackageprintpackage
There are two cases:
$ python package/test.py
['/Users/laike9m/Dev/Python/TestPython/package',
'/usr/local/lib/python2.7/site-packages/doc2dash-2.1.0.dev0-py2.7.egg',
'/usr/local/lib/python2.7/site-packages/zope.interface-4.1.3-py2.7-macosx-10.10-x86_64.egg',
'/usr/local/lib/python2.7/site-packages/six-1.10.0-py2.7.egg',
'/usr/local/lib/python2.7/site-packages/colorama-0.3.3-py2.7.egg',
As you see, path[0]
is /Users/laike9m/Dev/Python/TestPython/package
, which is the directory containing the script test.py
that was used to invoke the Python interpreter.
$ python
Python 2.7.12 (default, Jun 292016, 14:05:02)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits"or"license"for more information.
>>> import package
['',
'/usr/local/lib/python2.7/site-packages/doc2dash-2.1.0.dev0-py2.7.egg',
'/usr/local/lib/python2.7/site-packages/zope.interface-4.1.3-py2.7-macosx-10.10-x86_64.egg',
'/usr/local/lib/python2.7/site-packages/six-1.10.0-py2.7.egg',
'/usr/local/lib/python2.7/site-packages/colorama-0.3.3-py2.7.egg',
...
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 to PythonTest
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
.
Post a Comment for "Importerror: No Module Named Package"