我已经在我的 mac (10.8) 上安装了 requests 包,就像其他任何带有 pip 的包一样。

我可以在 /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages 下看到它。

但是,当我在 python 脚本中使用 import requests 时,出现终端错误:ImportError: No module named requests 就好像它没有安装一样。

Easy install 说它也安装了:

$ easy_install requests
Searching for requests
Best match: requests 1.2.3
Adding requests 1.2.3 to easy-install.pth file

Using /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages
Processing dependencies for requests
Finished processing dependencies for requests

我能找到的唯一错误是使用 pip 升级时:
$ pip install requests --upgrade
Downloading/unpacking requests
  Real name of requirement requests is requests
  Downloading requests-1.2.3.tar.gz (348Kb): 348Kb downloaded
  Running setup.py egg_info for package requests

Installing collected packages: requests
  Found existing installation: requests 1.2.3
    Uninstalling requests:
      Successfully uninstalled requests
  Running setup.py install for requests

      File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/requests/packages/urllib3/contrib/ntlmpool.py", line 38
        """
         ^
    SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 130-132: truncated \uXXXX escape

Successfully installed requests
Cleaning up...

为什么不能导入的一些想法?谢谢

最佳答案

这似乎是 urllib3 中的一个错误。查看源代码,从引发错误的文件的第 33 行开始:

def __init__(self, user, pw, authurl, *args, **kwargs):
    """
    authurl is a random URL on the server that is protected by NTLM.
    user is the Windows user, probably in the DOMAIN\username format.
    pw is the password for the user.
    """

字符串中间的 \u 是非法的。我不会从 import requests 甚至 import requests.packages.urllib3 得到这个错误,但如果我 import requests.packages.urllib3.contrib.ntlmpool ,我也会得到它。

我不知道为什么它会自动为你导入 ntlmpool,但这并不重要;这绝对是一个错误。

该错误于 2013 年 5 月 22 日在 change 1f7f39cb 中的 urllib 中修复,并于 2013 年 6 月 8 日合并到 change 2ed976ea 中的 requests 作为 issue 1412 的一部分。但它仍然存在于 1.2.3 版本中,这是截至 2013-07-05 的最新版本 on PyPI。您可以在 issue 1416 中找到更多信息,该信息已通过评论“修复应该很快发布”而关闭。

所以,你有三个选择:
  • 等待 1.2.4。
  • pip install git+https://github.com/kennethreitz/requests 从 github 安装树顶代码,而不是最后一个官方版本。
  • 编辑 /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages/requests/packages/urllib3/contrib/ntlmpool.py 的本地副本以转义第 38 行的反斜杠。

  • 代码应如下所示:
    def __init__(self, user, pw, authurl, *args, **kwargs):
        """
        authurl is a random URL on the server that is protected by NTLM.
        user is the Windows user, probably in the DOMAIN\\username format.
        pw is the password for the user.
        """
    

    关于python - 请求包 python 未导入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17483975/

    10-14 17:41