How do I set environment variables in pipenv?

user1283776 picture user1283776 · Jul 7, 2018 · Viewed 26.5k times · Source

I need to set some access token environment variables for my python project that I am running in a pipenv. I will want to set these environment variables every time I start the pipenv.

How do I do this?

Answer

PRMoureu picture PRMoureu · Jul 8, 2018

If you want to load automatically some environment variables each time you start the project, you can set a .env file at the root folder of the project, next to the Pipfile. See Automatic Loading of .env.

You can run the following command from the right folder to create this .env file :

echo MY_TOKEN=SuperToKen >.env  # create the file and write into
echo MY_VAR=SuperVar >>.env     # append to the file

or just create it manually to obtain:

MY_TOKEN=SuperToKen
MY_VAR=SuperVar

This file will be loaded automatically with pipenv shell or pipenv run your_command and the environment variables will be available.

You can access/check them in your code with :

print(os.getenv('MY_TOKEN', 'Token Not found'))

Not sure about other IDE, but within Pycharm you need the plugin Env File to load it automatically (access Env File tab from the Run/Debug configurations).


You can add comments in this file with a leading #

# My test token
MY_TOKEN=SuperToKen

Note : Of course you must exclude this file from your version control (like git).