python – How to set environment variables in PyCharm?

python – How to set environment variables in PyCharm?

You can set environmental variables in Pycharms run configurations menu.

  1. Open the Run Configuration selector in the top-right and cick Edit Configurations...

    Edit

  2. Find Environmental variables and click ...

    Environmental

  3. Add or change variables, then click OK

    Editing

You can access your environmental variables with os.environ

import os
print(os.environ[SOME_VAR])

I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.

The installation is pretty simple:

Preferences > Plugins > Browse repositories… > Search for Env File > Install Plugin.

Then, I created a file, in my project root, called environment.env which contains:

DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1

Then I went to Run->Edit Configurations, and I followed the steps in the next image:

Set

In 3, I chose the file environment.env, and then I could just click the play button in PyCharm, and everything worked like a charm.

python – How to set environment variables in PyCharm?

This functionality has been added to the IDE now (working Pycharm 2018.3)

Just click the EnvFile tab in the run configuration, click Enable EnvFile and click the + icon to add an env file

Example

Update: Essentially the same as the answer by @imguelvargasf but the the plugin was enabled by default for me.

Leave a Reply

Your email address will not be published.