In the standard Python Console or Terminal in PyCharm it is pretty straightforward to set environment variables.
How can you set environment variables for PyCharm's managed Jupyter?
In the standard Python Console or Terminal in PyCharm it is pretty straightforward to set environment variables.
How can you set environment variables for PyCharm's managed Jupyter?
There is no easy built-in way at the moment, I am afraid. See the corresponding ticket in the JetBrains issue tracker https://youtrack.jetbrains.com/issue/DS-2770 (and vote for it).
The one workaround that comes to mind is to export the desired environment variables in a shell session -> start PyCharm from it -> start the managed server. IDE will inherit the envs from the shell, and the server will inherit them from the IDE.
You can use a configured Jupyter Server.
Open a terminal in PyCharm
Export your environment variables in the terminal
export MY_VARIABLE="its-value"
Start a Jupyter Server
jupyter notebook --no-browser
Configure PyCharm to use the server you just started
Note the server URL from the terminal output and then add a server configuration in Languages & Frameworks => Jupyter => Jupyter Servers
More a workaround than a solution, one can use python-dotenv
.
Put an .env
file with the variables in the directory of the notebook and in the code
from dotenv import load_dotenv
load_dotenv()
More on this in this question.
A typical .gitignore
will exclude .env
files from a git repo.
The downside is the dependency to python-dotenv
(although the import can be try/excepted if not needed in production).
This feature was added to PyCharm 2023.2 (see this issue and the changelog) but it is restricted to PyCharm Pro.