How to set environment variables in PyCharm?
Asked Answered
D

12

171

I have started to work on a Django project, and I would like to set some environment variables without setting them manually or having a bash file to source.

I want to set the following variables:

export DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
export DEBUG=1
# there are other variables, but they contain personal information

I have read this, but that does not solve what I want. In addition, I have tried setting the environment variables in Preferences-> Build, Execution, Deployment->Console->Python Console/Django Console, but it sets the variables for the interpreter.

Dragonhead answered 10/3, 2017 at 1:11 Comment(3)
Setting variables in pycharm has one disadvantage, that is you lose them if you delete the profile. An alternative is just to set a default value like the following import os os.getenv(key='DATABASE_URL', default='postgres://127.0.0.1:5432/my_db_name')Banuelos
I think if you use the approach mentioned in my answer you won't lose the environment variables since they will be in the file you use. This answer is not addressing the question since it refers how to set them in PyCharm not if they are lose or not.Dragonhead
I also do not consider a good idea to hardcode values directly in code. This is a very bad practice.Dragonhead
D
260

You can set environmental variables in Pycharm's run configurations menu.

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

Edit Configurations...

  1. Select the correct file from the menu, find Environmental variables and click ...

Environment variables

  1. Add or change variables, then click OK

Editing environmental variables

You can access your environmental variables with os.environ

import os
print(os.environ['SOME_VAR'])
Draconic answered 10/3, 2017 at 1:19 Comment(7)
oh, I was just trying to type on that line, the triple dot looked grayed out so i didn't even think to click on it.Purpure
I tried this method but PyCharm doesn't pick the defined env var (I specifically tried to set DATABASE_URL). Looks like a PyCharm bug.Geithner
@Geithner in PyCharm there are two places where we can set env variables. One is for running environment(and it sets how Joran showed) and also we can set variables which will be available for console in Pycharm(and it sets here Preferences -> Build, Execution, Deployment -> Console -> Python Console )Wille
Yeh this seems like the right answer to me. I would add that if you set the environmental variable in the Defaults/Python config, then it will be used every time you right-click on a script and run itAeromechanics
This worked for me. Had to restart my interpreter first though.Gadfly
why doesn't work this in my PyCharm 2021.2.1 (Professional Edition), using on Ubuntu 18.04.6 bionic. This clearly 'simle things' not working that's so frustrating. Printing out sorted(os.environ.items()) from inside django.conf.__init__ doesn't even lists PYTHONUNBUFFERED - very frustrating.Prohibitionist
If it doesn't work make sure you've set the variables for the correct category in step 2. (i accidentally didn't set it on "Python" but on "Flask")Hedda
D
174

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 Environment Variables

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.

Dragonhead answered 10/3, 2017 at 1:19 Comment(11)
@Dragonhead I can't thank you enough for this answer. It looks like Pycharm can't pick up env vars sources in .bashrc (I'm on Linux). This plugin saved me a lot of time as I can use postactivate file as source.Fruition
@Dragonhead yes, sorry. I mean 2017.2.4Wage
Working here on 2017.3. Thanks!Overwrought
Working in 2017.2Perm
too bad it does not see .env file, i had to rename it to dev.envCore
@krinker, are you on Mac OS?Dragonhead
Yes. I added this to the Finder so now I can see .env there, but even after restarting PyCharm, I still don't see it when I browse through PyCharm ``` defaults write com.apple.finder AppleShowAllFiles YES. ```Core
@krinker, when you are browsing for the file, please press, cmd + shift+. to show the hidden files.Dragonhead
Anyone got this to work with the Python Console and Terminal too? It seems quite useless to me to only be able to set it for the runtime environment, but none of the other subfunctionalities.Boethius
Please keep in mind .env variables can not be defined with export. For example REDIS_HOST=localhost, but if you will define with export REDIS_HOST=localhost then it will not work.Liew
This is broken in the most recent version of Professional Edition.Wilbanks
P
37

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 (in Settings):

  • Tools > Terminal > Environment variables
  • Languages & Frameworks > Django > Environment variables
  • Build, Execution, Deployment > Console > Python Console > Environment variables
  • Build, Execution, Deployment > Console > Django Console > Environment variables

and of course, your run/debug configurations that was already mentioned.

Pebble answered 14/1, 2022 at 22:1 Comment(3)
This answer is the best here IMO. The only thing I'm missing is how to set it so that it also applies to django_test_manage.py.Chirlin
Thank you - variables from python run config don't translate to the console, or the terminal either. So this is very important to understand, you essentially have to set them in multiple places.Leaseback
This is indeed a good answer!Precincts
D
20

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 with the glorious material theme

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

Dressingdown answered 15/3, 2019 at 9:59 Comment(5)
I am pycharm 2019, and I don't see the tab EnvFile. Is this available in Python configuration (your screenshot is DjangoServer)?Walkerwalkietalkie
he has the "EnvFile" plugin installed.Hargrave
this solution did not work for pycharm 2021Prostatectomy
did not work for PyCharm 2022.2.2 (Professional Edition)Lilywhite
Worked in 2022.3.2 (Requires the EnvFile plugin)Yesteryear
B
7

This is what you can do to source an .env (and .flaskenv) file in the pycharm flask/django console. It would also work for a normal python console of course.

  1. Do pip install python-dotenv in your environment (the same as being pointed to by pycharm).

  2. Go to: Settings > Build ,Execution, Deployment > Console > Flask/django Console

  3. In "starting script" include something like this near the top:

    from dotenv import load_dotenv
    load_dotenv(verbose=True)

The .env file can look like this: export KEY=VALUE

It doesn't matter if one includes export or not for dotenv to read it.

As an alternative you could also source the .env file in the activate shell script for the respective virtual environement.

Bestir answered 31/12, 2020 at 0:30 Comment(1)
thank you, this answer actually addresses the env being in the terminal and not just in the run config.Callisto
H
3

Let's say the environment variables are in a file and store like below. Copy all of them to clipboard Ctrl+A -> Ctrl+C

Environment Variables

Then click on Edit Configurations -> Environment Variables. PyCharm Env settings

Now click on the small paste icon, and all the environment variables, will be available for usage in current environment. enter image description here

Horbal answered 3/2, 2023 at 5:2 Comment(0)
R
1

None of the above methods worked for me. If you are on Windows, try this on PyCharm terminal:

setx YOUR_VAR "VALUE"

You can access it in your scripts using os.environ['YOUR_VAR'].

Romilda answered 26/9, 2020 at 7:14 Comment(0)
E
1

This method helped me a lot for calling environmental variable from a .env file and its really easy to implement too.

  1. Create a .env file in the root folder of the project

  2. Install a package called "python-dotenv"

  3. Import and load the package in the .py file where you want to use the environment variable as follows

     import os
     from dotenv import load_dotenv, find_dotenv
    
     load_dotenv(find_dotenv())
     any_secret_var = os.get_env("SECRET_KEY")
    

and BOOM it will work like magic

And the .env file should look like, don't place any qoutes around the values in the .env file

    SECRET_KEY=any_secret_value_you_need_to_place_in
Edmee answered 28/1, 2022 at 10:0 Comment(0)
V
1

In case anyone want to set environment variables for all their Run/Debug Configuration, I list my solution here.

  1. Go to the Edit Configurations as pointed by other answers.
  2. Click edit the configuration templates in the panel.
  3. Edit environment variables there.

By doing so, the variables will be there every time you create a new configuration.

Villainage answered 22/6, 2022 at 21:22 Comment(0)
M
0

Solution tested with virtual environment.

Create an script that define and export or source the env vars. Then define the script as the python interpreter of an existing virtual env. The solution works for any task like run, debug, console ...

Example script:

#!/bin/bash


DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export VAR1="TEST1"
source $DIR/../../.env
$DIR/python "$@"
Mckenzie answered 24/4, 2022 at 7:34 Comment(0)
V
0

This is the best way to set environment variable in pycharm terminal. Just add the following lines at the end of venv/bin/activate script if you are using a virtual environment:

export $(grep -v '^#' .env | xargs)
Voluminous answered 28/5, 2023 at 18:11 Comment(0)
L
-2

In the Pycharm Python console just type

ENV_VAR_NAME="STRING VARIABLE"
INT_VAR_NAME=5

Unlike other Python text editors, you do not add export in Pycharm

Linzer answered 10/7, 2021 at 11:54 Comment(1)
That's not working!Coquille

© 2022 - 2024 — McMap. All rights reserved.