Python os.getenv() Method
Imran Alam
Jan 30, 2023
Python
Python OS
-
Syntax of
os.getenv(): -
Example Codes: Use the
os.getenv()Method to Get the Environment Variable Value -
Example Codes: Use the
os.getenv()Method With the Default Parameter -
Example Codes: Possible Error While Using the
os.getenv()Method
The os.getenv() method is a built-in function in the OS module. It is used to obtain the value of an environment variable.
Syntax of os.getenv():
os.getenv(key, default=None)
Parameters
key |
This is the environment variable’s name. |
default (optional) |
This is the value returned if the environment variable is not found. The default value is None. |
Return
The os.getenv() method returns the value of the environment variable.
Example Codes: Use the os.getenv() Method to Get the Environment Variable Value
In the following example, we will get the value of the data environment variable.
import os
data = "VARIABLE"
path = os.getenv(data)
print(path)
Output:
This will return the value of the VARIABLE environment variable.
Example Codes: Use the os.getenv() Method With the Default Parameter
In the following example, we will get the value of the USERNAME environment variable. The default value (Guest) will be returned if the environment variable is not found.
import os
username = os.getenv("DATA", "Guest")
print(username)
Output:
Guest
Example Codes: Possible Error While Using the os.getenv() Method
If the key is not a string, then a TypeError will be raised. In the following example, we will try to get the value of an environment variable with an integer key.
import os
os.getenv(1)
Output:
TypeError: the key must be a string
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe