VS 代码调试总是在 Python 中的内部模块上给出 ImportError

VS Code debugging always gives ImportError on internal modules in Python

我回答了我自己的问题,请参阅下面的解决方案。把这一切都留给后代,因为我做了很多其他人说有用并且为他们工作过的东西,但 none 确实有效。

问题

下面是一个非常简单的 python 文件。当尝试在此文件上使用 Visual Studio Code 的调试器时,我总是在任何内部模块上得到一个 ImportError,例如 app.modelsapp.tests.scripts.stubs。如果这些模块在 faker 或任何其他外部模块下方列出,调试器将通过外部模块而不抛出错误,但会在 app.models 或首先列出的任何内部模块上抛出错误。在我试过的 8-10 个文件中都是如此。

我试过的

我已经在 launch.json 和用户设置中指定了确切的 python路径,如下所示。我添加了 "exceptionHandling" 以忽略 ImportErrors。我已经卸载并重新安装了 Don Jayamanne 出色的 Python 扩展。我已经 运行 Python: Select Workspace Interpreter 并将其指向 ./.venv/bin/python2.7./.venv/bin/python2 和 ``./.venv/bin/python`.

文件

launch.jsonPython配置

    "name": "Python",
    "type": "python",
    "request": "launch",
    "stopOnEntry": false,
    "pythonPath": "/Users/REDACTED/REDACTED/.venv/bin/python2.7",
    "program": "${file}",
    "cwd": "${workspaceRoot}",
    "env": null,
    # we have 10+ environmental shell scripts, so I can't really use "envFile" in
    # a meaningful way, though I have tried pointing it at one of the shell scripts
    # but was still unable to debug.
    "envFile": "${workspaceRoot}/.venv",
    "debugOptions": [
        "WaitOnAbnormalExit",
        "WaitOnNormalExit",
        "RedirectOutput"
    ],
    "exceptionHandling": {
        "ignore": [
            "ImportError"
        ]
    }
},

Python 文件

from app.models import Kelly
import app.tests.scripts.stubs
from faker import Faker
import factory
from datetime import datetime
from bson.objectid import ObjectId

fake = Faker()

kelly_names = [REDACTED]


class KellyFactory(factory.Factory):
    class Meta:
        model = Kelly
    id = ObjectId()
    is_archived = False
    email = factory.LazyAttribute(
        lambda kel: '%s@email.com' % kel.name.split()[0])
    name = fake.word(ext_word_list=kelly_names)
    phone = fake.phone_number()
    date_last_modified = datetime.now()


kelly = KellyFactory()

解决方案

在遍历我所做的一切时,针对 post 这个问题,我尝试将路径 program"${file}" 更改为绝对路径。这使调试器可以毫无错误地超越导入。然后我遇到了一个问题,因为我不在任何环境中,所以我在我的机器上进入了一个 dev 环境,尽管我不必在 VSCode 中更改任何其他内容。但是,我现在遇到了一个 unverified breakpoint 问题,我正在寻找这个问题。一旦我弄明白了就会更新。

我尝试解决未验证断点问题的方法

我将 "program" 改回 "${file}",调试工作完全符合预期,断点有效,在这样一个超级简单的文件上

import sys
print(sys.version)
print(sys.executable)

然而,尽管在 launch.json 中指定了 "exceptionHandling",但在原始问题中上面列出的 Python 文件等更复杂的文件再次导致 ImportError .