Python – How to set environment variables in Python

environment-variablespython

I need to set some environment variables in the Python script and I want all the other scripts that are called from Python to see the environment variables' set.

If I do,

os.environ["DEBUSSY"] = 1

it complains saying that 1 has to be a string.

I also want to know how to read the environment variables in Python (in the latter part of the script) once I set it.

Best Answer

Environment variables must be strings, so use

os.environ["DEBUSSY"] = "1"

to set the variable DEBUSSY to the string 1.

To access this variable later, simply use:

print(os.environ["DEBUSSY"])

Child processes automatically inherit the environment variables of the parent process -- no special action on your part is required.