Set Environment Variable in Python Script

All environment variables (both system and user variables) can be assessed on the os.environ attribute in Python.

The attribute returns a dictionary of all environment variables with keys as the variable names and values as environment values. The resulting dictionary supports all the operations of a native Python dictionary.

This article focuses on setting environment variables – temporarily for the current Python session and permanently for persistent variable change.

Printing Environment Variables

Output (truncated):

environ({'KDE_FULL_SESSION': 'true', 'USER': 'kiprono', 'LC_TIME': 'en_US.UTF-8', 'XDG_SEAT': 'seat0', 'SSH_AGENT_PID': '1704', 'XDG_SESSION_TYPE': 'x11', 'XCURSOR_SIZE': '24', 'SHLVL': '1', 'HOME': '/home/kiprono',...)

Accessing a Variable

You can use os.getenv(<var>) or os.environ.get(<var>) to get the value of <var>. For example,

Output:

/home/kiprono
None
/home/kiprono/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin

Setting Environment Variable

Just like you would do a native Python dictionary, you can set environment variable using the syntax os.environ[<variable>] = new_environment_value.

The following example sets the $HOME variable into a new path.

Output:

/home/kiprono
/home/kiprono/Desktop

As shown in the output, the $HOME directory has been updated. Note that if the environment variable did not exist already, the method above would create it.

Important Note

The change made on the environment variable(s) using the method above will only exist for the current session of the Python interpreter.

If you want the changes on the environment to persist after ending the Python session, you must edit the user profile.

We can do that with the following code syntax.

Note (for Windows): The code above changes the variables <var> for the current user. If you want the variables to be available for global usage, use “setx /M <var> ‘value’” (it may need elevation of privileges).

Note (for Mac OS): The profile might be located in the .profile or .bash_profile file on the home directory instead of the .bashrc.

Conclusion

This article discussed two ways of setting environment variables using Python. The first changes the environment for the current Python session, and the last section discusses how to make permanent changes to the environment variables.