Python 3

home

Environment Variables

Environment Variables

A computer's variables are stored on a local computer, and thus can be controlled and secured locally.


Used here, a computer environment is a general term meaning the configuration settings that a computer, or computer session, use to adjust its behavior. Your environment may specify where programs are located in your filesystem, which programs may take precedence over others, and passwords used to access secured systems. Your computer may maintain many settings (such as Windows' Registry), but among them are environment variables, which are specific key/value pairs that specify some of these settings. These variables are stored on your individual computer or the computer you are working with. You may maintain environment variables that apply to all users of your system, or just to you.





Retrieving Environment Variables through Python

We can use os.getenv() or os.environ to retrieve environment variables.


In each of these examples, MY_PASSWORD is a sample environment variable key.

import os

# dynamically retrieve key/value pair from environment
val = os.getenv('MY_PASSWORD')

# equivalent, uses a dict that contains all key/value pairs
val = os.environ['MY_PASSWORD']




Setting Environment Variables on Your Computer

The specific steps will depend on your platform and OS Version.


Windows (Note that if these instructions don't work for your version of Windows, you can find many tutorials, including screenshots, online.)




Mac/Linux





[pr]