首页 > 解决方案 > python2.7下调试导入requests模块的脚本时vscode报异常

问题描述

环境

macOS Big Sur 版本 11.6

python2.7

Visual Studio 代码:版本 1.61.0

问题

例如,我有一个名为 test.py 的非常简单的 python 文件。其中的脚本如下:

import requests
print "ok"

我把test.py放在一个文件夹test里,vscode用来打开这个文件夹,选择python2.7作为解释器,然后Start Debugging在菜单中选择调试test.py with vscode

但是,vscode会告诉我一个错误。

Exception has occurred: AttributeError       (note: full exception trace is shown but execution is paused at: __getattr__)
'module' object has no attribute '__path__'
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/cryptography/utils.py", line 135, in __getattr__ (Current frame)
    obj = getattr(self._module, attr)
  File "/Library/Python/2.7/site-packages/urllib3/contrib/pyopenssl.py", line 155, in _validate_dependencies_met
    from OpenSSL.crypto import X509
  File "/Library/Python/2.7/site-packages/urllib3/contrib/pyopenssl.py", line 118, in inject_into_urllib3
    _validate_dependencies_met()
  File "/Library/Python/2.7/site-packages/requests/__init__.py", line 96, in <module>
    pyopenssl.inject_into_urllib3()
  File "/Users/malong/Desktop/test/test.py", line 1, in <module>
    import requests
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 82, in _run_module_code
    mod_name, mod_fname, mod_loader, pkg_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 252, in run_path
    return _run_module_code(code, init_globals, run_name, path_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)

但是如果我选择Run Without Debugging,脚本可以成功执行。“ok”这个词将打印在嵌入式终端中。

如果我requests用任何其他模块替换该模块,脚本也可以正常调试。

这个问题只能在python2.7下重现。python3.x下是可以的。它也可以在我朋友的电脑上复制,所以我想这是一个常见的问题。

标签: python-2.7visual-studio-codepython-requestsvscode-debugger

解决方案


推荐阅读