Environment variables, as the name suggests, are variables in your system that can affect the way running processes will behave on a computer. It is actually a combination of values, called key/pair values . The most well known environment variable is probably PATH which contains the paths to all folders that might contain executables. The concept of environment variables exists in most operating systems , from Linux to OS X to Windows. In Python, environment variables are accessed through os.environ .

import os
print(os.environ['PATH'])

How to set and get environment variables in Python?

In order to set and get environment variables in Python you can just use the following code:

import os
# Set environment variables
os.environ['API_USER'] = 'newuser'
os.environ['API_PASSWORD'] = 'mypass'

# Get environment variables
USERNAME = os.getenv('API_USER')
PASSWORD = os.environ.get('API_PASSWORD')

Dictionary Operations

Python os.environ behaves like a python dictionary, so all the common dictionary operations can be performed.
Environment Variables in Python
If you want to see a list of all the environment variables use the following code:

>>> print(os.environ)
The following program will print all of the environment variables along with their values .

import os
for key, value in os.environ.items():
    print('{}: {}'.format(key, value))

How to check environment variables exists in Python?


import os
import sys
try:
   os.environ["MYVAR"]
except KeyError:
   print("Please set the environment variable MYVAR")
   sys.exit(1)

Or


import os
if ('PATH' in os.environ):
  print("Key exist")
else:
  print("Key does not exist")
Prev
Index Page
Next
©Net-informations.com