For Flask apps, you can create a launch.json configuration that will run your Flask app using VS Code's debugger. VS Code's launch.json supports a number of options, including the setting of environment variables that your Flask app needs.

Start with installing the Python extension for VS Code, to add support for "debugging of a number of types of Python applications, which includes Flask. Then, follow the Flask Tutorial from the VS Code docs.

Basically, you'll need to create a launch.json file in your workspace's .vscode folder.

{
    // 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": "run-flask-app",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "/path/to/app.py",
                "FLASK_ENV": "development",
                "FLASK_DEBUG": "0",
                "AAA": "value of AAA env var",
                "BBB": "value of BBB env var",
                "CCC": "value of CCC env var"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ],
            "jinja": true
        },
    ]
}

The env portion is where you set all the environment variables. By default, it includes the required FLASK_*-related variables because it uses the flask command line tool for running apps.

Here, as an example, I've also set custom AAA and BBB and CCC vars. You can access that from code as normal env vars:

@app.route('/test')
def root():
    aaa = os.environ.get("AAA")
    bbb = os.environ.get("BBB")
    ccc = os.environ.get("CCC")
    print(f'{aaa}, {bbb}, {ccc}')
    return f'{aaa}, {bbb}, {ccc}'

Then run it from the Debug panel:

Just hit the play button and you should be able to see the printed env values from the Terminal panel or from the browser after accessing the /test endpoint. (If you have multiple terminals, it should appear under the Python Debug Console).

Lastly, by saving the .vscode/launch.json file under the workspace folder, then it's workspace-specific, and it will only affect the runtime environment used to launch your Flask app.

Answer from Gino Mempin on Stack Overflow
Top answer
1 of 2
21

For Flask apps, you can create a launch.json configuration that will run your Flask app using VS Code's debugger. VS Code's launch.json supports a number of options, including the setting of environment variables that your Flask app needs.

Start with installing the Python extension for VS Code, to add support for "debugging of a number of types of Python applications, which includes Flask. Then, follow the Flask Tutorial from the VS Code docs.

Basically, you'll need to create a launch.json file in your workspace's .vscode folder.

{
    // 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": "run-flask-app",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "/path/to/app.py",
                "FLASK_ENV": "development",
                "FLASK_DEBUG": "0",
                "AAA": "value of AAA env var",
                "BBB": "value of BBB env var",
                "CCC": "value of CCC env var"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ],
            "jinja": true
        },
    ]
}

The env portion is where you set all the environment variables. By default, it includes the required FLASK_*-related variables because it uses the flask command line tool for running apps.

Here, as an example, I've also set custom AAA and BBB and CCC vars. You can access that from code as normal env vars:

@app.route('/test')
def root():
    aaa = os.environ.get("AAA")
    bbb = os.environ.get("BBB")
    ccc = os.environ.get("CCC")
    print(f'{aaa}, {bbb}, {ccc}')
    return f'{aaa}, {bbb}, {ccc}'

Then run it from the Debug panel:

Just hit the play button and you should be able to see the printed env values from the Terminal panel or from the browser after accessing the /test endpoint. (If you have multiple terminals, it should appear under the Python Debug Console).

Lastly, by saving the .vscode/launch.json file under the workspace folder, then it's workspace-specific, and it will only affect the runtime environment used to launch your Flask app.

2 of 2
1

In our case, I found that using "type": "python" works, but if you do "type": "debugpy", environment variables set in the env part of each element in the configurations array of launch.json aren't read.

TLDR: use "type": "python.

🌐
Visual Studio Code
code.visualstudio.com › docs › python › environments
Python environments in VS Code
November 3, 2021 - By default, the debugger uses your selected environment. To use a different interpreter for debugging, set the python property in your launch.json debug configuration.
Discussions

Setting environment variable in VS Code debugger
How to set environment variables in VS Code debugger in launch.json for Julia? For Python, the env var can be set by the “env” property: { "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": ... More on discourse.julialang.org
🌐 discourse.julialang.org
1
0
April 24, 2023
node.js - How do I add environment variables to launch.json in VS Code? - Stack Overflow
I'm working with Visual Studio Code on a Node.js project. I am attempting to configure my "Launch" profile for debugging by editing the launch.json file. I need to setup a connection stri... More on stackoverflow.com
🌐 stackoverflow.com
How to forward environment variables from shell I to launch.json
One way to do it could be to set the environment variable in the environment your program launches in. For example when running inside a dev container, in the devcontainer.json. There the syntax is something lik ${var_on_host} More on reddit.com
🌐 r/vscode
3
4
May 4, 2023
Specifying the Python interpreter in launch.json using the CONDA_PREFIX environment variable raises an error
Type: Bug The following configuration launch.json sets the Python interpreter to the Python interpreter of the activated conda environment of the integrated terminal { // Use IntelliSense to learn ... More on github.com
🌐 github.com
8
May 12, 2023
🌐
GitHub
github.com › microsoft › vscode-python › issues › 6986
launch.json environment variables not being passed to Python scripts · Issue #6986 · microsoft/vscode-python
August 16, 2019 - Environment variables configured in launch.json are sometimes set when a python script is run or debugged. Sometimes they are not. ... "configurations": [ { "name": "Python: current jobs", "type": "python", "request": "launch", "program": ...
Author   duncanw
🌐
Visual Studio Code
code.visualstudio.com › docs › python › debugging
Python debugging in VS Code
November 3, 2021 - When set to true, ensures that a Pyramid app is launched with the necessary pserve command. Sets optional environment variables for the debugger process beyond system environment variables, which the debugger always inherits. The values for these variables must be entered as strings. Optional path to a file that contains environment variable definitions. See Configuring Python environments - environment variable definitions file.
🌐
Reddit
reddit.com › r/vscode › how to forward environment variables from shell i to launch.json
r/vscode on Reddit: How to forward environment variables from shell I to launch.json
May 4, 2023 -

Hi, I already know how to set environment variables in launch.json.

What I can’t figure out is how to have it read environment variables from my shell. My AWS credentials get cycled a lot and I was to do something like

“env” : { AWS_SESSION_TOKEN: “${AWS_SESSION_TOKEN}”

So the debugger pulls the variables from the current shell. Is there any way to do that?

It’s not finding them currently and I’m losing my mind running thing without a debugger.

🌐
GitHub
github.com › microsoft › vscode-python-debugger › issues › 158
Specifying the Python interpreter in launch.json using the CONDA_PREFIX environment variable raises an error · Issue #158 · microsoft/vscode-python-debugger
May 12, 2023 - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Dynamic path", "type": "python", "request": "launch", "program": "myscript.py", "console": "integratedTerminal", "cwd": ".", "python": "${env:CONDA_PREFIX}/bin/python", "justMyCode": true }, ] } Wenn I activate the conda environment with the path to the Python interpreter being /conda/envs/my_env/bin/python and then start the debugger of this configuration, I get the following output in the terminal · /usr/bin/env /conda/envs/my_env/bin/python /home/.vscode-server/extensions/ms-python.python-2023.8.0/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher 45096 -- myscript.py -X is reserved for implementation-specific arguments usage: /bin/python [option] ...
Published   May 12, 2023
Author   FSpanhel
Find elsewhere
🌐
Visual Studio Code
code.visualstudio.com › docs › debugtest › debugging-configuration
Visual Studio Code debug configuration
1 week ago - For example, to specify the application entry point, attach to a running application, or set environment variables. Creating a launch configuration file is also beneficial because it allows you to configure and save debugging setup details with your project. VS Code stores debugging configuration information in a launch.json file located in the .vscode folder in your workspace (project root folder), or in your user settings or workspace settings.
🌐
Visual Studio Code
code.visualstudio.com › docs › editor › variables-reference
Variables reference
July 24, 2023 - Use IntelliSense inside string values for tasks.json and launch.json to get a full list of predefined variables.
🌐
Donjayamanne
donjayamanne.github.io › pythonVSCodeDocs › docs › debugging
Debugging | Python in Visual Studio Code
Whether this is set or not, the debugger process will inherit the environment variables. ... The extension supports debugging of a number of types of python applications. However these are in active development. The following debugging capabilities are supported: ... Debugging a standard python application is possible by adding the standard configuration settings in the launch.json file as follows:
Top answer
1 of 5
32

You do not need to add activate to launch.json. You have 3 options (I prefer the first option):

  1. Provide the complete path to python in the virtual environment. Here is one of my launch configurations. The python entry points to the python executable image in a virtual environment.

        {
          "justMyCode": false,
          "name": "Ancient Warmth / Django-Oscar",
          "type": "python",
          "request": "launch",
          "program": "${workspaceFolder}/manage.py",
          "python": "${env:oscar}/bin/python",
          "args": [
            "runserver",
            "--noreload",
            "0.0.0.0:8001",
          ],
          "django": true
        },
    

    Note that the above refers to an environment variable called oscar that points to the virtual environment. I define oscar in .bashrc like this:

    export oscar=/var/work/django/oscar
    

    It does not matter where the environment variable is defined, so long as it is defined before VSCode runs.

  2. At the bottom of the VSCode window, near the left side, you will find the name of the Python environment being used.

    a. Click on it and a list of the workspaces drops down from the top.

    b. Select the workspace that you want to modify the Python for, then you will see a list of Python interpreters. The one you want is probably not shown, so click on "I can't find the interpreter I want to select...", then click "Find...".

    c. Navigate to your virtual environment and click on python.

  3. This option is a manual way of producing the same change as option #2. Edit the file called .vscode/settings.json in your project directory and set python.pythonPath to point to the python program in your virtual environment. Here is my complete .vscode/settings.json file:

    {
      "python.linting.pylintEnabled": true,
      "python.linting.enabled": true,
      "python.pythonPath": "/var/work/django/oscar/bin/python"
    }
    
2 of 5
10

Mike Slinn's answer pointed me in the right direction but if you are a Windows user of venv, this is exactly what I did.

Open the launch.json and add the following:

 "python":"C:/Users/[pathto]/[projectfolder]/.venv/Scripts/python.exe"

Full File:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "python": "C:/Users/cullen/pathto/projectfolder/.venv/Scripts/python.exe",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": true
        }
    ]
}
🌐
Medium
reuvenharrison.medium.com › using-visual-studio-code-to-debug-a-go-program-with-environment-variables-523fea268271
Debugging go in vscode with environment variables | by Reuven Harrison | Medium
August 30, 2020 - Open settings.json and add this at the top level: "go.testEnvVars": { "LOG_LEVEL": "debug", }, All your tests will now receive this environment variable. To start, you need to configure launch.json: { "version": "0.2.0", "configurations": [ ...
Top answer
1 of 3
4

Here is an example, you set the value in the environment block.

    {
// 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": "g++ - (GDB 9.2) Build and debug active file with RepoCodeInspection",
        "type": "cppdbg",
        "request": "launch",
        "program": "${fileDirname}/bin/${fileBasenameNoExtension}",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [
            {
                "description": "same as commands below by using 'setenv ...",
                "info": "cant debug b/c of libBase/libRecipe now requiring dependency to boost for stacktrace dumps",
                "name": "LD_LIBRARY_PATH",
                "value": "/libs/:./"
            }
        ],
        "externalConsole": false,
        "MIMode": "gdb",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ],
        "logging": {
            "trace": false,
            "traceResponse": false
        },
        "preLaunchTask": "RepoCodeInspection",
        
    },
    {
        "name": "g++ - (GDB 9.2) Attach to a running process",
        "type": "cppdbg",
        "request": "attach",
        "processId":"${command:pickProcess}",
        "program": "${fileDirname}/bin/${fileBasenameNoExtension}",
        "MIMode": "gdb",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ],
        "logging": {
            "trace": false,
            "traceResponse": false
        },
        "preLaunchTask": "RepoCodeInspection",
       
    },
]

}

2 of 3
3

To set multiple environment variables, use comma-separated "name", "value" pairs.

Example:

"environment": [{"name": "LD_LIBRARY_PATH", "value": "/ld/library/path/"},
                {"name": "CUDA_VISIBLE_DEVICES", "value": "0"}
               ]
🌐
Donjayamanne
donjayamanne.github.io › pythonVSCodeDocs › docs › python-path
Python Path and Version | Python in Visual Studio Code
Unfortunately use of relative paths when configuring the interpreter in settings.json will not work with the debugger. Hence the solution is to provide the fully qualified path. This could be achieved with the use of simple variables such as the following: Where ${workspaceRoot} resolves to the current work space (project) directory. { "python.pythonPath": "${workspaceRoot}/venv/bin/python" } Similar to the use of ${workspaceRoot}, environment variables could be used in configuring the path to the python interpreter.
🌐
YouTube
youtube.com › watch
How to Add Environment Variables to launch.json in VSCODE - YouTube
👍 Don't forget to like, comment, and subscribe to stay updated with more coding tips and tricks! 🚀 In this video, I’ll walk you through the steps to add en...
Published   December 5, 2024
Top answer
1 of 3
2

Using launch.json, I am not able to access the modified PYTHONPATH. In both interactive mode and Run mode, the path doesn't reflect the desired changes.

If you're running the file using the play button at the top right or its dropdown entries, or using the Python: Run Python File in Terminal or Jupyter: Run Current File in Interactive Window commands in the command palette, those don't pick on things you put in your launch.json configs as far as I know. You need to actually run the launch config from the Run and Debug View, select the launch config you want to run, and then click the play button in the Run and Debug View.

If you insist on using the Python: Run Python File in Terminal command, or actions based on that command, you can look into using the terminal.integrated.env.* VS Code settings- either in your user or workspace settings.json file. Ex.

"terminal.integrated.env.linux": {
    "PYTHONPATH": "${workspaceFolder}/conf/",
}

I'm not sure about workarounds for Jupyter notebooks though.

2 of 3
1

After diving deeper into docs and other SO posts, and with hints from @JaileDu's and @user's answers, I've found the complete solution to the problem in the OP.

For interactive mode, need to add the following to settings.json (change .osx to respective OS in your case:

"terminal.integrated.env.osx": {"PYTHONPATH": "${workspaceFolder}"},
"jupyter.notebookFileRoot": "${workspaceFolder}"

For Run mode, set PYTHONPATH in .env file (documented here) or launch.json (see the same documentation page and this blogpost).


Some related SO posts:

  • Relative imports for the billionth time
  • How to correctly set PYTHONPATH for Visual Studio Code
  • How to set the import path for the the Python Interactive window in VS Code?
  • add a python path to a module in visual studio code
  • Default Python paths when using VSCode interactive window
Top answer
1 of 2
9

Inspired by my current area of work - which involved Python.

This is what I do for Flask.

MS Link

https://code.visualstudio.com/docs/python/debugging

For any regular Python debugging

Evidence

import os

for key in os.environ.keys():
    print(f"{key}={os.environ.get(key)}")

After doing a F5 in VS Code with a file containing the above snippet:

Update on Feb 18

After receiving a comment I think the OP wants to run a script before debugging the Fask application. The steps that worked for me are below.

Overview

I ended up with the following files:

  • Add a PowerShell file dosomething.ps1 (my custom script which I intend to launch before every debug session)
  • Add a task.json (launch dosomething.ps1)
  • Edit the existing launch.json by linking it with the task in task.json

The file dosomething.ps1

Write-Host "Inside do something"
Write-Host "The value of the environment variable TEMP is $env:TEMPcls"
Write-Host "The current path of the script is $PSScriptroot"

The file tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "my script task",
            "type": "shell",
            "windows": {
                "command": "pwsh -f dosomething.ps1"
            },
            "problemMatcher": []
        }
    ]
}

Linking the launch.json with task.json

After pressing F5


What if my environment variable is a secret that I do not want to add to launch.json ?

In my team, we place all confidential variables in a .env file and add the file to .gitignore. As per design of VS Code, it will look for a .env file in the root of the current workspace and load those variables before launching your Python script. Please refer documentaion from MS here: https://code.visualstudio.com/docs/python/environments

By default, the Python extension looks for and loads a file named .env in the current workspace folder, then applies those definitions. The file is identified by the default entry "python.envFile": "${workspaceFolder}/.env" in your user settings (see General Python settings). You can change the python.envFile setting at any time to use a different definitions file

2 of 2
5

I had a similar problem and could solve it by setting environment variables in the "env" field of the launch.JSON file. This shoudl be stored in a .vscode folder in your project root, here is the docs: https://code.visualstudio.com/docs/python/debugging

I discovered the "env" field in this snippet here: https://gist.github.com/slaveofcode/b4c18efc99c16029913cde3fd2dba3ce

Not sure how to configure this dynamically with the -option A -option B however. Hope this helps :)

🌐
Visual Studio Code
code.visualstudio.com › docs › cpp › launch-json-reference
Configure C/C++ debugging
November 3, 2021 - JSON array of command-line arguments to pass to the program when it is launched. Example ["arg1", "arg2"]. If you are escaping characters, you will need to double escape them. For example, ["{\\\"arg1\\\": true}"] will send {"arg1": true} to ...
🌐
CodeGenes
codegenes.net › blog › use-environment-variables-in-vs-code-launch-configurations
How to Use Environment Variables in VS Code Launch Configurations (launch.json) – Simplify Sharing with Coworkers
As developers, we rely heavily on **environment variables** to manage configuration, sensitive data (like API keys or database passwords), and environment-specific settings (e.g., `NODE_ENV=development` vs. `production`). When working in teams, sharing debugging setups—especially in VS Code—can become a headache: hard-coded variables in `launch.json` lead to merge conflicts, accidental exposure of secrets, or coworkers struggling to replicate your local environment.