Skip to main content
 首页 » 编程设计

python之如果文件名为 email.py 或 logging.py,则无法使用 Python Requests 模块

2025年05月04日15jpfss

我有一个简单的测试脚本:

import requests 
response = requests.get('http://httpbin.org/get') 
print response.text 

当 python 脚本命名为 test.py 时有效,但如果命名为 email.py 或 logging.py 则失败:

Traceback (most recent call last): 
  File "./email.py", line 3, in <module> 
    import requests 
  File "/usr/lib/python2.7/dist-packages/requests/__init__.py", line 53, in <module> 
    from urllib3.contrib import pyopenssl 
  File "/usr/lib/python2.7/dist-packages/urllib3/__init__.py", line 16, in <module> 
    from .connectionpool import ( 
  File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 59, in <module> 
    from .request import RequestMethods 
  File "/usr/lib/python2.7/dist-packages/urllib3/request.py", line 12, in <module> 
    from .filepost import encode_multipart_formdata 
  File "/usr/lib/python2.7/dist-packages/urllib3/filepost.py", line 15, in <module> 
    from .fields import RequestField 
  File "/usr/lib/python2.7/dist-packages/urllib3/fields.py", line 7, in <module> 
    import email.utils 
  File "/home/ubuntu/temp/email.py", line 4, in <module> 
    response = requests.get('http://httpbin.org/get') 
AttributeError: 'module' object has no attribute 'get' 

requests 似乎导入了 urllib3,后者导入了 email 内置模块。为什么 Python 找不到 the built-in email module first , 而不是在当前路径中查找 email.py?

有没有办法让它工作,或者我是否只需要始终避免将我的 Python 脚本命名为任何可能由任何依赖项导入的内置模块?

请您参考如下方法:

首先,正如您在评论中指出的那样,Python 检查该名称的“内置”模块。并非标准库中的所有模块都是“内置”的。您可以通过以下方式查看列表:

print sys.builtin_module_names 

如果在那里找不到,搜索的顺序由 Burhan 在此处接受的答案概述:

What is the extent of the import statement in Python

Python searches for things it can import in the following order:

  • From the directory where the script was executed.
  • From the directories in the PYTHONPATH environment variable (if its set).
  • From the system-wide Python installation's module directory.

在您的例子中,电子邮件不是内置的,因此首先检查当前目录。

所以,是的,不要隐藏 python 库名称。从技术上讲,您可以隐藏内置模块的名称,但请不要这样做。它让 Python 哭泣。