In Python Interactive using the #%%
cell designator for .py
files, I frequently use os.getenv("VAR")
to test code that uses environment variables. My interpreter is a Python virtual environment. I am frequently adding and removing environment variables to my environment startup script at source $HOME/env/bin/activate
like so:
export VAR="value"
To get the variables to work in VS Code Interactive, I have to use Developer: Reload Window
which means I lose all my data on the Interactive window. Is there a way apply environment variables to the Python Interactive instance without modifying the env/bin/activate
script (which requires a reload)?
2
Answers
You can read docs about environment variables.
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 . You can change the python.envFile setting at any time to use a different definitions file.Example:
dev.env:
MYPROJECT_DBUSER=devadmin
test.py:
settings.json:
When I run test.py by using an interactive window, I get
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 saydev.env
and one for prod sayprod.env
. To add these, in your workspace folder you may see a folder.vscode
, it may have two fileslaunch.json
andsettings.json
.launch.json
is used for debugging andsettings.json
is for setting up your workspace settings.Example of
launch.json
In
settings.json
: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: