python file without extension works, but with .py extension fails to import my module
My python file has "from .. import" statement to package under C:\Python27\Lib\site-packages.
If my file name does not have any e开发者_如何学运维xtension (e.g. foo ) then "python foo" works. If I rename file from foo to foo.py then the "from .. import" statement to that package fails in foo.py:try: from my_package.System.prefix import ... except ImportError: print "ERROR: Could not import modules."
I have:
PYTHONPATH=C:\Python27\Lib\site-packages Environment: Windows XP/ Python 2.7I'm going to make a wild guess here: is your filename the same as the package that you're trying to import (my_package
in your example)?
I was able to reproduce behavior similar to what you describe by creating a file, django.py
, that contained the import statement from django.db import models
. When I ran python django.py
, I got ImportError: No module named db
. When I moved code to a file named django
(without a .py extension), deleted the django.pyc
file, and ran python django
, the import succeeded.
Why Python tries to import the django
module, it starts by looking for a django.py
file in the directory that contains the program being executed. In the first case, it imports the django.py
file that I created instead of the django
module that's installed in site-packages
. In the second case, where I renamed my file django
, Python can't find a django.py
in the same directory as my file, so it properly import django
from site-packages
.
精彩评论