Previous Page
Next Page

14.6. Process Environment

The operating system supplies each process P with an environment, which is a set of environment variables whose names are identifiers (most often, by convention, uppercase identifiers) and whose contents are strings. In "Environment Variables" on page 22, I covered environment variables that affect Python's operations. Operating system shells offer ways to examine and modify the environment via shell commands and other means mentioned in "Environment Variables" on page 22.

The environment of any process P is determined when P starts. After startup, only P itself can change P's environment. Nothing that P does affects the environment of P's parent process (the process that started P), nor of those of child processes previously started from P and now running, nor of processes unrelated to P. Changes to P's environment affect only P itself: the environment is not a means of IPC. Child processes of P normally get a copy of P's environment as their starting environment. In this sense, changes to P's environment do affect child processes that P starts after such changes.

Module os supplies attribute environ, which is a mapping that represents the current process's environment. os.environ is initialized from the process environment when Python starts. Changes to os.environ update the current process's environment if the platform supports such updates. Keys and values in os.environ must be strings. On Windows, but not on Unix-like platforms, keys into os.environ are implicitly uppercased. For example, here's how to try to determine which shell or command processor you're running under:

import os shell = os.environ.get('COMSPEC')
if shell is None: shell = os.environ.get('SHELL')
if shell is None: shell = 'an unknown command processor'
print 'Running under', shell

When a Python program changes its environment (e.g., via os.environ['X']='Y'), this does not affect the environment of the shell or command processor that started the program. As already explained, and for all programming languages including Python, changes to a process's environment affect only the process itself, not others.


Previous Page
Next Page