How do I set environment variables in pipenv?

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).