Environment variables are useful to store sensitive data like API keys or passwords when we don't want them to be hard coded in our source code. But we often only use them in some specific circumstances and don't need to have them set all the time. In this short post, I am going to show how to save environment variables in a virtual environment set using conda.
First, we need to create the virtual environment using the
conda create command:
$ conda create --name my_environment
This command will create a
my_environment subdirectory in the
Next, we activate the environment:
$ source activate my_environment (my_environment)$
Now, we need to create scripts that will set our environment variables whenever we activate our virtual environment and unset them when we deactivate. The path to our environment directory is set as
cd to that directory and create a
/etc/conda/activate.d and a
(my_environment)$ cd $CONDA_PREFIX (my_environment)$ mkdir -p ./etc/conda/activate.d (my_environment)$ mkdir -p ./etc/conda/deactivate.d
In each of those directories, we create a
env_var.sh script where we'll write the commands to set and unset our variables:
(my_environment)$ touch ./etc/conda/activate.d/env_vars.sh (my_environment)$ touch ./etc/conda/deactivate.d/env_vars.sh
activate.d/env_vars.sh, we add the
export commands to set our variables when the virtual environment is activated:
#!/bin/sh export MY_VARIABLE=some_value
deactivate.d/env_vars.sh, we add the
unset commands to delete our variables when the virtual environment in deactivated.
#!/bin/sh unset MY_VARIABLE
Let's test our setting. We need to reactivate our environment to get the variables set.
(my_environment)$ conda deactivate $ conda activate my_environment (my_environment)$ echo $MY_VARIABLE some_value
The environment variable has been set. Now, let's check if the variable is unset when we deactivate our environment:
(my_environment)$ conda deactivate $ echo $MY_VARIABLE $
echo command returns an empty line, meaning that our variable has been unset.
Voilà! We now have a virtual environment with it's own environment variables.