How to Set Environment Variables in Python


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,


# Import module
import os

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

Python Errors

str expected, not int:

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

Related Tags