奇怪的 Python 导入错误

Weird Python import errors

我遇到了这个非常奇怪的错误,我在从 AWS EMR 的主目录启动的 Python shell 中收到导入错误,而相同的包在以下情况下导入正常我 cd 进入另一个目录并在那里启动 Python shell。

EMR 已安装 Python 2.7。请让我知道我可以提供哪些额外信息。这个问题快把我逼疯了!

$ python
Python 2.7.16 (default, Mar 18 2019, 18:38:44)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import smtplib
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/smtplib.py", line 46, in <module>
    import email.utils
  File "email.py", line 2, in <module>
    from email.mime.multipart import MIMEMultipart
ImportError: No module named mime.multipart
>>> os.path.realpath('./')
'/home/abc123'
>>>
$ mkdir temp
$ cd temp
[temp]$ python
Python 2.7.16 (default, Mar 18 2019, 18:38:44)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import smtplib
>>> os.path.realpath('./')
'/home/abc12/temp'

第一个(主)目录中是否有名为 email.py 的文件?或者名为 email 的文件夹?如果是,那么这可能会影响导入行为,因为 python 的查找机制(应用根目录优先于其他导入)。

来自 docs:(强调我的)

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.