python os.environ()和os.getenv()方区别
os.environ() 如果环境变量不存在,则引发异常。
os.getenv() 不引发异常,但返回None。os.getenv() 读取环境变量。比如,os.getenv('PATH')
Python | os.environ object
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.environ in Python is a mapping object that represents the user’s environmental variables. It returns a dictionary having user’s environmental variable as key and their values as value.
os.environ behaves like a python dictionary, so all the common dictionary operations like get and set can be performed. We can also modify os.environ but any changes will be effective only for the current process where it was assigned and it will not change the value permanently.
Syntax: os.environ
Parameter: It is a non-callable object. Hence, no parameter is required
Return Type: This returns a dictionary representing the user’s environmental variables
Code #1: Use of os.environ to get access of environment variables
| # Python program to explain os.environ object  # importing os module importosimportpprint # Get the list of user's# environment variablesenv_var =os.environ # Print the list of user's# environment variablesprint("User's Environment variable:")pprint.pprint(dict(env_var), width =1) | 
{'CLUTTER_IM_MODULE': 'xim',
 'COLORTERM': 'truecolor',
 'DBUS_SESSION_BUS_ADDRESS': 'unix:path=/run/user/1000/bus',
 'DESKTOP_SESSION': 'ubuntu',
 'DISPLAY': ':0',
 'GDMSESSION': 'ubuntu',
 'GJS_DEBUG_OUTPUT': 'stderr',
 'GJS_DEBUG_TOPICS': 'JS '
                     'ERROR;JS '
                     'LOG',
 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated',
 'GNOME_SHELL_SESSION_MODE': 'ubuntu',
 'GTK_IM_MODULE': 'ibus',
 'HOME': '/home/ihritik',
 'IM_CONFIG_PHASE': '2',
 'JAVA_HOME': '/opt/jdk-10.0.1',
 'JOURNAL_STREAM': '9:28586',
 'JRE_HOME': '/opt/jdk-10.0.1/jre',
 'LANG': 'en_IN',
 'LANGUAGE': 'en_IN:en',
 'LESSCLOSE': '/usr/bin/lesspipe '
              '%s '
              '%s',
 'LESSOPEN': '| '
             '/usr/bin/lesspipe '
             '%s',
 'LOGNAME': 'ihritik',
 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:
/usr/local/games:/snap/bin:/usr/local/java/jdk-10.0.1/bin:
/usr/local/java/jdk-10.0.1/jre/bin:/opt/jdk-10.0.1/bin:/opt/jdk-10.0.1/jre/bin',
 'PWD': '/home/ihritik',
 'QT4_IM_MODULE': 'xim',
 'QT_IM_MODULE': 'ibus',
 'SESSION_MANAGER': 'local/hritik:@/tmp/.ICE-unix/1127, unix/hritik:/tmp/.ICE-unix/1127',
 'SHELL': '/bin/bash',
 'SHLVL': '2',
 'SSH_AUTH_SOCK': '/run/user/1000/keyring/ssh',
 'TERM': 'xterm-256color',
 'TEXTDOMAIN': 'im-config',
 'TEXTDOMAINDIR': '/usr/share/locale/',
 'USER': 'ihritik',
 'USERNAME': 'ihritik',
 'VTE_VERSION': '4804',
 'WAYLAND_DISPLAY': 'wayland-0',
 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/etc/xdg',
 'XDG_CURRENT_DESKTOP': 'ubuntu:GNOME',
 'XDG_MENU_PREFIX': 'gnome-',
 'XDG_RUNTIME_DIR': '/run/user/1000',
 'XDG_SEAT': 'seat0',
 'XDG_SESSION_DESKTOP': 'ubuntu',
 'XDG_SESSION_ID': '2',
 'XDG_SESSION_TYPE': 'wayland',
 'XDG_VTNR': '2',
 'XMODIFIERS': '@im=ibus',
 '_': '/usr/bin/python3'}
Code #2: Accessing a particular environment variable
| # Python program to explain os.environ object  # importing os module importos # Get the value of# 'HOME' environment variablehome =os.environ['HOME'] # Print the value of# 'HOME' environment variableprint("HOME:", home) # Get the value of# 'JAVA_HOME' environment variable# using get operation of dictionaryjava_home =os.environ.get('JAVA_HOME') # Print the value of# 'JAVA_HOME' environment variableprint("JAVA_HOME:", java_home) | 
HOME: /home/ihritik JAVA_HOME: /opt/jdk-10.0.1
Code #3: Modifying a environment variable
| # Python program to explain os.environ object  # importing os module importos  # Print the value of# 'JAVA_HOME'  environment variable print("JAVA_HOME:", os.environ['JAVA_HOME']) # Modify the value of# 'JAVA_HOME'  environment variable os.environ['JAVA_HOME'] ='/home / ihritik / jdk-10.0.1' # Print the modified value of# 'JAVA_HOME' environment variableprint("Modified JAVA_HOME:", os.environ['JAVA_HOME']) | 
JAVA_HOME: /opt/jdk-10.0.1 Modified JAVA_HOME: /home/ihritik/jdk-10.0.1
Code #4: Adding a new environment variable
| # Python program to explain os.environ object  # importing os module importos # Add a new environment variable os.environ['GeeksForGeeks'] ='www.geeksforgeeks.org' # Get the value of# Added environment variable print("GeeksForGeeks:", os.environ['GeeksForGeeks']) | 
GeeksForGeeks: www.geeksforgeeks.org
Code #5: Accessing a environment variable which does not exists
| # Python program to explain os.environ object  # importing os module importos # Print the value of# 'MY_HOME' environment variable print("MY_HOME:", os.environ['MY_HOME']  # If the key does not exists# it will produce an error | 
Traceback (most recent call last):
  File "osenviron.py", line 8, in 
    print("MY_HOME:", os.environ['MY_HOME'])
  File "/usr/lib/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'MY_HOME'
Code #6: Handling error while Accessing a environment variable which does not exists
| # Python program to explain os.environ object   # importing os module importos # Method 1# Print the value of# 'MY_HOME' environment variable print("MY_HOME:", os.environ.get('MY_HOME', "Environment variable does not exist"))  # Method 2try:    print("MY_HOME:", os.environ['MY_HOME'])exceptKeyError:     print("Environment variable does not exist") | 
MY_HOME: Environment variable does not exist Environment variable does not exist
Python | os.getenv() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.getenv() method in Python returns the value of the environment variable key if it exists otherwise returns the default value.
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.
Code #1: use of os.getenv() method
| # Python program to explain os.getenv() method    # importing os module importos # Get the value of 'HOME'# environment variablekey ='HOME'value =os.getenv(key) # Print the value of 'HOME'# environment variableprint("Value of 'HOME' environment variable :", value)  # Get the value of 'JAVA_HOME'# environment variablekey ='JAVA_HOME'value =os.getenv(key) # Print the value of 'JAVA_HOME'# environment variableprint("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
Code #2: if key does not exist
| # Python program to explain os.getenv() method    # importing os module importos # Get the value of 'home'# environment variablekey ='home'value =os.getenv(key) # Print the value of 'home'# environment variableprint("Value of 'home' environment variable :", value) | 
Value of 'home' environment variable : None
Code #3: Explicitly specifying default parameter
| # Python program to explain os.getenv() method    # importing os module importos # Get the value of 'home'# environment variablekey ='home'value =os.getenv(key, "value does not exist") # Print the value of 'home'# environment variableprint("Value of 'home' environment variable :", value)  | 
Value of 'home' environment variable : value does not exist
 
                    
                     
                    
                 
                    
                 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号