按 F5 使用 VS Code 调试 Python 模块

Jam*_*ndy 9 python visual-studio-code

我的项目结构如下:

Project Folder
--setup.py
----Module Folder
------ __init__.py
------ __main__.py
Run Code Online (Sandbox Code Playgroud)

我的__main__.py文件包含我的应用程序的入口点,安装文件的配置如下:

from setuptools import setup

setup(name='my_project',
      version='0.1.0',
      packages=['my_project'],
      entry_points={
          'console_scripts': [
              'my_project= my_project.__main__:main'
          ]})
Run Code Online (Sandbox Code Playgroud)

这意味着我可以在不附加调试器的情况下运行我的代码,使用:

python -m my_project
Run Code Online (Sandbox Code Playgroud)

I've tried debugging using VS Code by navigating to my __main__.py file and pressing F5 to run but this doesn't work and throws an exception. How do I configure Visual Studio Code to run this module in debug mode? Also how do I ensure the program also runs the module and not the file I am looking at when I press F5?

gri*_*tin 6

接受的答案对我不起作用(VSCode 1.49.0),并且我收到一条错误消息:Invalid message: "program", "module", and "code" are mutually exclusive

删除"program": "${file}",线解决了问题。我认为这是有道理的,因为定义模块(带有隐含的入口点)和文件是多余的。

我的launch.json看起来像这样:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Module",
            "type": "python",
            "request": "launch",
            "console": "integratedTerminal",
            "module": "my_project",
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)


Jam*_*ndy 5

After some research I've found a solution:

  1. Navigate to the top right section in the debug menu and click the cog to create a launch.json file for this project. This will be used to configure VS Code.

配置 VS 代码

  1. If there isn't one already a launch.json file be created, into it paste this:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Module",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "pythonPath": "${config:python.pythonPath}",
            "module": "my_project",
            "cwd": "${workspaceRoot}",
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

I found this code here: https://github.com/DonJayamanne/pythonVSCode/issues/518#issuecomment-260838308

  1. Just using this answer didn't work for me though and I got the error: No module named my_projectbut I found this answer: https://github.com/DonJayamanne/pythonVSCode/issues/826 In it the final comment tells you add the following to the config.

    "env": {"PYTHONPATH":"${workspaceRoot}"},
    
    Run Code Online (Sandbox Code Playgroud)

This fixes the error and now you can press F5 and your module will be debugged.