The above solution works, but if you change the environment variables in your .env
file, you still have to reload the window.
One way to avoid that would be define all the environment variables in the .env
file, but that could lead to many-many environment variables.
vs-code recommends to setup two .env
files, one for debugging say dev.env
and one for prod say prod.env
. To add these, in your workspace folder you may see a folder .vscode
, it may have two files launch.json
and settings.json
. launch.json
is used for debugging and settings.json
is for setting up your workspace settings.
Example of launch.json
{
// 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": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true,
"python.envFile": "${workspaceFolder}/dev.env"
}
]
}
In settings.json
:
{
"python.envFile": "${workspaceFolder}/prod.env"
}
For launch.json
to take effect, you will have to start up your session in your debugging mode.
Again, if you change your environment variables in above mentioned files, you still have to reload the window or restart the kernel for new environment variables to show up, leading you to lose your data on interactive window. If you want to keep your data and still want to change environment variables, you can do so by os.environ[key]=var
. If in case you have many variables to add/change, you can as following:
# store your environment variables in json (or config.ini) as key value pair
# following assumes you store your environment variable in json file
import os
import json
env_vars = json.load(open('env_file.json', 'r'))
for key, value in env_vars.items():
os.environ[key]=value