[Python](EN) Get environment variable

Post about get environment variable


Environment and Prerequisite

  • Python 3.X or higher


Get Environment Variable

Use os Module

Basic Form

  • Returns the environment variable key if it exists.
  • If key does not exists, then return default value.
  • If default is not set and environment variable of key does not exists, then return None.
  • Return type of environment variable is str.
os.getenv(key, default=None)

Example

  • Set environment variable
export TEST="TEST env value"
export NUM=123
  • Get environment variable
>>> import os
>>> os.getenv("TEST", "TEST env default value")
'TEST env value'
  • Check return type
>>> import os
>>> type(os.getenv("NUM", "NUM env default value"))
<class 'str'>
  • Get default if key does not exists
>>> import os
>>> os.getenv("default", "TEST env default value")
'TEST env default value'
>>> type(os.getenv("default", "TEST env default value"))
<class 'str'>
>>> import os
>>> os.getenv("default", 12345)
12345
>>> type(os.getenv("default", 12345))
<class 'int'>
  • Return None if both key and default does not exists
>>> import os
>>> type(os.getenv("NONE TEST"))
<class 'NoneType'>


Reference