How do I set environment variables in pipenv?

Question:

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?

Asked By: user1283776

||

Answers:

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

Answered By: PRMoureu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.