Installing requirements.txt in a venv inside VSCode

Question:

Apart from typing out commands – is there a good way to install requirements.txt inside VSCode.

I have a workspace with 2 folders containing different Python projects added – each has it’s own virtual environment. I would like to run a task to execute and install the requirements to each of these.

I have tried adding a task to tasks.json to try and do it for one with no success.

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Service1: Install requirements",
            "type": "shell",
            "runOptions": {},
            "command": "'${workspaceFolder}/sources/api/.venv/Scripts/activate'; pip install -r '${workspaceFolder}/sources/api/requirements.txt'",
            "problemMatcher": []
        }
    ]
}

This runs – but you can see it refer to my global Python packages h:program filespython311libsite-packages – not the virtual environment.

I am running on Windows for this – but would like it to work eventually with Linux.

Asked By: andrewthedev

||

Answers:

I’ve written a more detailed post before, but as Andez mentioned in comments, this is also a suitable post for the answer. This task can be ran in Windows, Linux and MacOS.

{

    "version": "2.0.0",
    "tasks": [
        {
            "label": "Build Python Env",
            "type": "shell",
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "linux": {
                "options": {
                    "cwd": "${workspaceFolder}"
                },
                "command": "python3 -m venv py_venv && source py_venv/bin/activate && python3 -m pip install --upgrade pip && python3 -m pip install -r requirements.txt && deactivate py_venv"
            },
            "osx": {
                "options": {
                    "cwd": "${workspaceFolder}"
                },
                "command": "python3 -m venv py_venv && source py_venv/bin/activate && python3 -m pip install --upgrade pip && python3 -m pip install -r requirements.txt && deactivate py_venv"
            },
            "windows": {
                "options": {
                    "shell": {
                        "executable": "C:\Windows\system32\cmd.exe",
                        "args": [
                            "/d",
                            "/c"
                        ]
                    },
                    "cwd": "${workspaceFolder}"
                },
                "command": "(if not exist py_venv py -m venv py_venv) && .\py_venv\Scripts\activate.bat && py -m pip install --upgrade pip && py -m pip install -r requirements.txt && deactivate py_venv"
            },
            "problemMatcher": []
        }
    ]
}
Answered By: kyrlon