Python: Access Environment Variables

The Operating System Environment variables are dynamic values that can affect the behavior of programs and scripts running on the system.

If you are wondering how to access Environment Variables in your Python code, remember to make use of the os module.

The os.environ is a dictionary-like object in Python's os module which you can use to access the environment variables of the current operating system.

Let's take a look at some code examples (based on macOS):

Example 1:
import os
print(os.environ["CONDA_PYTHON_EXE"])

/Users/c2ctech/anaconda3/bin/python


Example 2:
import os
print(os.environ["HOME"])

/Users/c2ctech


Example 3:
import os
print(os.environ["HOMEBREW_PREFIX"])

//opt/homebrew

Print Environment Variables using Python Code

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!