How to Set Environment Variables in Python

How to set environment variables with python?

Ok so based on the comment above, to help future users who might not be aware of this, you cannot set environment variables outside the scope of the current process with Python.

You can make python aware of some variables and change env variables for the scope of a process and its child processes. But you can not set values for env in the system itself or other processes (that are not children of the current process). For example if I set a env variable called HOST_URL it wont be actually accessible in the system environment.

I found three ways to actually set the variables by:

  1. Running a bash script to set the env variable values
  2. Use VSCode launch.json for setting the variables either with env or envFile
  3. Define them through Docker file or docker-compose.yml if you are containerizing your app

Note:
If there are other options to address this please comment and I ll add them. I want this to be a helpfull post for new developers like myself. Shaming and non-helpful comments never helped anyone or improved anything. This is, or should be, a learning and knowledge exchange platform and it should be open to all programming questions Stack Overflow Isn’t Very Welcoming. It’s Time for That to Change

How to set environment variables in PyCharm?

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

  1. Open the Run Configuration selector in the top-right and cick 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'])

How to set env variable in Jupyter notebook

To set an env variable in a jupyter notebook, just use a % magic commands, either %env or %set_env, e.g., %env MY_VAR=MY_VALUE or %env MY_VAR MY_VALUE. (Use %env by itself to print out current environmental variables.)

See: http://ipython.readthedocs.io/en/stable/interactive/magics.html

How to set environment variables in GitHub actions using python

You cannot set environment variables directly. Instead, you need to write your environment variables into a file, whose name you can get via $GITHUB_ENV.

In a simple workflow step, you can append it to the file like so (from the docs):

echo "{name}={value}" >> $GITHUB_ENV

In python, you can do it like so:

import os

env_file = os.getenv('GITHUB_ENV')

with open(env_file, "a") as myfile:
myfile.write("MY_VAR=MY_VALUE")

Given this python script, you can set and use your new environment variable like the following:

- run: python write-env.py
- run: echo ${{ env.MY_VAR }}


Related Topics



Leave a reply



Submit