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 OverflowFor 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.
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.
Setting environment variable in VS Code debugger
node.js - How do I add environment variables to launch.json in VS Code? - Stack Overflow
How to forward environment variables from shell I to launch.json
Specifying the Python interpreter in launch.json using the CONDA_PREFIX environment variable raises an error
I'm successfully passing them using the env property in launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/index.js",
"env": {
"TEST_VAR": "foo"
}
}
]
}
This is working

just add the following:
"env": {
"NODE_ENV": "development"
}
As shown below:
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program", //TODO: cmd as launch program
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\index.js",
"env": {
"NODE_ENV": "development"
}
}
]
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.
You do not need to add activate to launch.json. You have 3 options (I prefer the first option):
Provide the complete path to
pythonin the virtual environment. Here is one of my launch configurations. Thepythonentry points to thepythonexecutable 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
oscarthat points to the virtual environment. I defineoscarin.bashrclike this:export oscar=/var/work/django/oscarIt does not matter where the environment variable is defined, so long as it is defined before VSCode runs.
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.This option is a manual way of producing the same change as option #2. Edit the file called
.vscode/settings.jsonin your project directory and setpython.pythonPathto point to thepythonprogram in your virtual environment. Here is my complete.vscode/settings.jsonfile:{ "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.pythonPath": "/var/work/django/oscar/bin/python" }
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
}
]
}
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",
},
]
}
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"}
]
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.
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
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.jsonby linking it with the task intask.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
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 :)