How to Set Environment Variables in Python

Created
Modified

Using os.environ Variable

os.environ behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get and set operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.

For example,

#!/usr/bin/python3

# Import module
import os

# Environment variables must be strings
os.environ["GIT_PATH"] = "/usr/local"
print(os.environ["GIT_PATH"])
/usr/local

Python Errors

str expected, not int:

os.environ["GIT_VER"] = 1
File "/usr/local/lib/python3.10/os.py", line 756, in encode
  raise TypeError("str expected, not %s" % type(value).__name__)
TypeError: str expected, not int

Related Tags