How does python read environment variables?

In Python, you can use osthe module's getenvor environmethod to read environment variables. Here is how the two methods are used:

  1. Use os.getenv: This method returns the value of the specified environment variable, or returns if the environment variable does not exist None.

    import os
    
    var = os.getenv('VAR_NAME')
    
  2. Use os.environ: This method returns a dictionary representing environment variables, which you can manipulate like a dictionary. If the environment variable you are trying to access does not exist, it will raise one KeyError.

    import os
    
    var = os.environ['VAR_NAME']
    

In both methods above, 'VAR_NAME' needs to be replaced with the actual environment variable name you want to read.

If you need to read environment variables in your Python program, I recommend using it os.getenv, because it will not raise an error if the variable does not exist, but return it None. This makes it easier to run your program without setting a specific environment variable, just provide a default value. For example:

import os

var = os.getenv('VAR_NAME', 'default_value')

Here, if the 'VAR_NAME' environment variable does not exist, varit will be assigned the value 'default_value'.

Guess you like

Origin blog.csdn.net/m0_57236802/article/details/131294151