Set an environment variable

EasyOS Module Programs · 3 of 49

Write a Python program to set an environment variable for the current process.

Advertisement
Output
testing
child sees: testing

Approach

  1. Assign to os.environ; child processes inherit it.

Solution

Python
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.

More os module programs

← All 49 OS Module Programs

Leave a Comment