VS代码| Python程序模块导入过程未发生

时间:2020-05-07 13:45:07

标签: python visual-studio-code

环境

我有一个VS Code中的Python快速入门,作为多根工作区的一部分。我已经手动添加了3个文件; tasks.json settings.json launch.json

意外行为

当我调试项目时,主脚本由于缺少模块而失败。这是因为在启动时,未安装 requirements.txt 中列出的模块。

Tasks.json

{
    "version": "2.0.0",
    "tasks": [
      {
        "label": "pipInstall",
        "type": "shell",
        "osx": {
          "command": "${config:python.pythonPath}/bin/python -m pip install -r requirements.txt"
        },
        "windows": {
          "command": "${config:python.pythonPath}\\Scripts\\python -m pip install -r requirements.txt"
        },
        "linux": {
          "command": "${config:python.pythonPath}/bin/python -m pip install -r requirements.txt"
        },
        "problemMatcher": [],
        "options": {
          "cwd": "${workspaceFolder}"
        }
      }
    ]
  }

Launch.json

    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}\\batch-python-quickstart\\src\\python_quickstart_client.py",
            "console": "integratedTerminal"
        }
    ]
}

Settings.json

{
    "python.pythonPath": "C:\\Python Virtual Environments\\myenvid\\.venv\\Scripts\\python.exe"
}

1 个答案:

答案 0 :(得分:0)

为什么未安装模块

由于未在 launch.json 中引用 tasks.json ,因此未安装require.txt文件中指定的模块。要在执行python应用之前执行任务,需要"preLaunchTask": "pipInstall"引用task.json中名为pipInstall的任务。

更改后的代码

注意:我还修复了一些错误的路径,并将虚拟环境移到了项目的外部外部的新目录。

Settings.json

{
    "python.pythonPath": "C:\\thepath\\.venv\\Scripts\\python.exe"
}

Launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}\\batch-python-quickstart\\src\\python_quickstart_client.py",
            "console": "integratedTerminal",
            "preLaunchTask": "pipInstall"
        }
    ]
}

Tasks.json

{
    "version": "2.0.0",
    "tasks": [
      {
        "label": "pipInstall",
        "type": "shell",
        "osx": {
          "command": "${config:python.pythonPath}/bin/python -m pip install -r requirements.txt"
        },
        "windows": {
          "command": "${config:python.pythonPath} -m pip install -r requirements.txt"
        },
        "linux": {
          "command": "${config:python.pythonPath}/bin/python -m pip install -r requirements.txt"
        },
        "problemMatcher": [],
        "options": {
          "cwd": "${workspaceFolder}\\batch-python-quickstart\\src"
        }
      }
    ]
  }

此外

可以通过在任务内部添加相同的依赖项属性来级联任务; "dependsOn": "othertasklabel"。一组构建步骤的理想选择。