Python os.getenv()
Python中的os.getenv()方法返回环境变量键的值(如果它存在,则返回默认值)。
语法:os.getenv(key, default = None)
参数:
key:表示环境变量名的字符串
Default(可选):字符串,表示key不存在时的默认值。如果省略,默认设置为“None”。
返回类型:该方法返回一个字符串,表示环境变量key的值。如果key不存在,则返回默认参数的值。
示例1
使用os.getenv()方法
# Python program to explain os.getenv() method
# importing os module
import os
# Get the value of 'HOME'
# environment variable
key = 'HOME'
value = os.getenv(key)
# Print the value of 'HOME'
# environment variable
print("Value of 'HOME' environment variable :", value)
# Get the value of 'JAVA_HOME'
# environment variable
key = 'JAVA_HOME'
value = os.getenv(key)
# Print the value of 'JAVA_HOME'
# environment variable
print("Value of 'JAVA_HOME' environment variable :", value)
输出:
Value of 'HOME' environment variable : /home/ihritik
Value of 'JAVA_HOME' environment variable : /opt/jdk-10.0.1
示例2
如果key不存在
# Python program to explain os.getenv() method
# importing os module
import os
# Get the value of 'home'
# environment variable
key = 'home'
value = os.getenv(key)
# Print the value of 'home'
# environment variable
print("Value of 'home' environment variable :", value)
输出:
Value of 'home' environment variable : None
示例3
显式指定默认参数
# Python program to explain os.getenv() method
# importing os module
import os
# Get the value of 'home'
# environment variable
key = 'home'
value = os.getenv(key, "value does not exist")
# Print the value of 'home'
# environment variable
print("Value of 'home' environment variable :", value)
输出:
Value of 'home' environment variable : value does not exist