Python Practice › OS Module Programs › Program 3
Set an environment variable
Write a Python program to set an environment variable for the current process.
Output
testing child sees: testing
Approach
- Assign to
os.environ; child processes inherit it.
Solution
import osimport subprocessimport sys os.environ["APP_MODE"] = "testing"print(os.environ["APP_MODE"])child = subprocess.run([sys.executable, "-c", "import os; print(os.environ['APP_MODE'])"], capture_output=True, text=True)print("child sees:", child.stdout.strip())Output
testing child sees: testing
Line by line
Line 5
The value lives only in this process and the processes it starts; it does not change system settings.
Learn the concept
New to this topic? Read the lesson, then come back.