First, see how Python looks for packages and modules. sys.path
A list of strings indicating the search path for the modules. Initialized from the PYTHONPATH environment variable, and also depends on the default setting.
These are the search paths. Therefore, if your module / package is located in one of sys.path , the python interpreter can find and import it. Doc says more:
As initialized at program startup, the first element 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 accessible (for example, if the interpreter is invoked interactively or if the script is read from standard input), path[0] is an empty string that first directs Python to search for modules in the current directory.
As an example, I used test.py
import sys; import pprint pprint.pprint(sys.path) from package import package print package
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 can see, path[0] is /Users/laike9m/Dev/Python/TestPython/package , which is the directory containing the test.py script that was used to invoke the Python interpreter.
$ python Python 2.7.12 (default, Jun 29 2016, 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 a second case arises when it is called interactively, " path[0] is an empty string that directs Python to search for modules in the current directory." What is the current directory? /Users/laike9m/Dev/Python/TestPython/ . (look that this is the path on my machine, this is equivalent to the path to PythonTest in your case)
Now you know the answers:
Why python package/test.py provided ImportError: No module named package ?
Because the interpreter does not "see" the packet. For the interpreter to know about the package package , PythonTest must be in sys.path , but this is not so.
Why does it work interactively?
Because PythonTest is now in sys.path , so the interpreter can find the package package .