如何配置 Visual Studio Code 以在 virtualenv 中调试 Django 应用程序?

问题描述 投票:0回答:4

我希望能够在 Visual Studio Code 中调试 Django 应用程序。我有一个 virtualenv,在 launch.json 文件中进行了更改,如下所示:

{
    "name": "Django",
    "type": "python",
    "request": "launch",
    "stopOnEntry": true,
    "pythonPath": "${workspaceRoot}/.venv/bin/python2.7",
    "program": "${workspaceRoot}/mysite/manage.py",
    "args": [
        "runserver"
    ],
    "debugOptions": [
        "WaitOnAbnormalExit",
        "WaitOnNormalExit",
        "DjangoDebugging",
        "RedirectOutput"
    ]
},

在代码中放置几个断点并运行它。不幸的是,执行并没有在带有断点的线上停止。我在没有 virtualenv 的情况下尝试了相同的操作,一切都很完美。

请指出我在这里做错了什么。

python django visual-studio-code
4个回答
22
投票

对我来说,以下 2 个更改有效

  1. 为pythonPath添加绝对路径
  2. 启动项目时使用
    "--noreload"
    选项

这是我的配置的相关部分

    {
        "name": "Django",
        "type": "python",
        "request": "launch",
        "stopOnEntry": true,
        "pythonPath": "/Users/xyz/Documents/dev/my_project/my_project_env/bin/python",
        "program": "${workspaceRoot}/manage.py",
        "args": [
            "runserver",
            "0.0.0.0:8080",
            "--noreload"                
        ],
        "debugOptions": [
            "WaitOnAbnormalExit",
            "WaitOnNormalExit",
            "RedirectOutput",
            "DjangoDebugging"
        ]
    },

6
投票

1) 按 CTRL + ,
2) 选择工作区设置
3) 在打开的设置文件中添加以下行。

"python.pythonPath": "path_to_your_env"


你完成了!


4
投票

这个官方教程适用于我的情况。

只需打开 VS Code 的“命令面板”并选择我的 Python 解释器到虚拟环境:

完整参考:https://code.visualstudio.com/docs/python/tutorial-django#_create-a-project-environment-for-the-django-tutorial


0
投票

如果您在另一台电脑的 Visual Studio Code 中打开现有代码,您可以:1)重新创建 venv 文件,然后复制粘贴除(pyvenv.cfg)之外的原始文件

# macOS/Linux
# You may need to run `sudo apt-get install python3-venv` first on Debian-based OSs
python3 -m venv .venv

# Windows
# You can also use `py -3 -m venv .venv`
python -m venv .venv

2)选择翻译员 https://code.visualstudio.com/docs/python/tutorial-django#_create-a-project-environment-for-the-django-tutorial

3)使用下面的launch.json:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        
        {
            "name": "Python: Django",
            "type": "debugpy",
            "request": "launch",
            "python":"${workspaceFolder}/venv/Scripts/python.exe",
            "program": "${workspaceFolder}\\manage.py",
            "args": [
                "runserver"
            ],
            "django": true,
            "justMyCode": true
        }
    ]
}
© www.soinside.com 2019 - 2024. All rights reserved.