python urllib error - AttributeError: 'module' object has no attribute 'request'

本秂侑毒 提交于 2019-12-05 22:34:28

This looks like a nasty coincidence.

TL;DR: Don’t name your script string.py.


So what’s happening here?

  1. You’re trying to import urllib.request.

  2. urllib.request tries to import http.client, which tries to import email.parser, which tries to import email.feedparser, which tries to import email.message, which tries to import email.utils, which tries to import email.charset, which tries to import email.quoprimime.

  3. email.quoprimime tries to import string, expecting it to be the standard Python string module—but since the current working directory has priority over the standard Python library directories, it finds your string.py instead and tries to import that.

  4. When importing your string.py, you try to import urllib.request. Since urllib.request is still being imported, you get back a skeleton urllib without a request attribute yet.

  5. Because your imported string.py then fails because it can’t find the request attribute, the exception starts propagating back up.

  6. But wait, there’s more! Since there was an error during an import, Ubuntu tries to be helpful by seeing if you’re missing a dpkg package. If so, it could say “hey, it looks like you’re missing this module; want to apt-get it?” So the mechanism for looking up the appropriate package is activated…

  7. …but the module for looking up the appropriate package itself depends on urllib.request, so it tries to import it, and again fails…

In short, because you picked string.py as a file name, you overrode the standard string module, which broke a lot of other modules, and even broke the module that was supposed to be helpful when you were missing a module, causing a whole lot of havoc. Fortunately the solution is easy: rename your script.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!