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
Update: Essentially the same as the answer by @imguelvargasf but the the plugin was enabled by default for me.
You can set environmental variables in Pycharm's run configurations menu.
- Open the Run Configuration selector in the top-right and cick
Edit Configurations...
- Select the correct file from the menu, find
Environmental variables
and click...
- Add or change variables, then click
OK
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:
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.
The original question is:
How to set environment variables in PyCharm?
The two most-upvoted answers tell you how to set environment variables for PyCharm Run/Debug Configurations - manually enter them in "Environment variables" or use EnvFile plugin.
After using PyCharm for many years now, I've learned there are other key areas you can set PyCharm environment variables. EnvFile won't work for these other areas!
Here's where ELSE to look:
- Tools > Terminal > Environment variables
- Languages & Frameworks > Django > Environment variables
- Settings > Build, Execution, Deployment > Console > Python Console > Environment variables
- Settings > Build, Execution, Deployment > Console > Django Console > Environment variables
and of course, your run/debug configurations that was already mentioned.