[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 returndefault
value. - If
default
is not set and environment variable ofkey
does not exists, then returnNone
. - 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
ifkey
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 bothkey
anddefault
does not exists
>>> import os
>>> type(os.getenv("NONE TEST"))
<class 'NoneType'>