I'm a Python newbie, so bear with me :)
I created a file called test.py with the contents as follows:
test.py
import sys
print sys.platform
print 2 ** 100
I then ran import test.py file in the interpreter to follow an example in my book.
When I do this, I get the output with the import error on the end.
win32
1267650600228229401496703205376
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named py
Why do I get this error and how do I fix it? Thanks!
-
You don't specify the extension when importing. Just do:
import test -
Instead of:
import test.pysimply write:
import testThis assumes test.py is in the same directory as the file that imports it.
-
As others have mentioned, you don't need to put the file extension in your import statement. Recommended reading is the Modules section of the Python Tutorial.
For a little more background into the error, the interpreter thinks you're trying to import a module named
pyfrom inside thetestpackage, since the dot indicates encapsulation. Because no such module exists (and test isn't even a package!), it raises that error.As indicated in the more in-depth documentation on the import statement it still executes all the statements in the
testmodule before attempting to import thepymodule, which is why you get the values printed out. -
This strange-looking error is a result of how Python imports modules.
Python sees:
import test.pyPython thinks (simplified a bit):
import module test.
- search for a test.py in the module search paths
- execute test.py (where you get your output)
- import 'test' as name into current namespace
import test.py
- search for file test/py.py
- throw ImportError (no module named 'py') found.
Because python allows dotted module names, it just thinks you have a submodule named
pywithin thetestmodule, and tried to find that. It has no idea you're attempting to import a file.cdleary : I think the terminology is technically "*module* named `py` within the `test` *package*". (Could be wrong, though!)
0 comments:
Post a Comment