Python| os.getenv() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
Python中的os.getenv()
方法返回环境变量键的值(如果存在),否则返回默认值。
Syntax: os.getenv(key, default = None)
Parameters:
key: string denoting the name of environment variable
default (optional) : string denoting the default value in case key does not exists. If omitted default is set to ‘None’.
Return Type: This method returns a string that denotes the value of the environment variable key. In case key does not exists it returns the value of default parameter.
代码 #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:如果键不存在
# 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