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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap