Premise: When configuring Alibaba Cloud Computing FC today, you need to configure 'Edit Environment Variables' and understand os.environ.#
First, the os.environ module in Python is a system module used to get and set operating system environment variables. It is a dictionary object that contains all the environment variables of the current process.#
-
The main difference between
os.environ['baidu_base_url']
andos.environ.get('table_index', os.environ.get('tableIndex', ''))
lies in the way they obtain the value of the environment variable and how they handle non-existent environment variables. -
os.environ['baidu_base_url']
directly obtains the value ofbaidu_base_url
from the system environment variables. If this environment variable does not exist, it will throw aKeyError
exception and the program will stop running. -
os.environ.get('table_index', os.environ.get('tableIndex', ''))
uses theos.environ.get()
method to obtain the value oftable_index
ortableIndex
from the system environment variables. If neither exists, it returns an empty string''
. This approach effectively avoids the program throwing an exception and stopping running due to non-existent environment variables.
Therefore, when obtaining the value of an environment variable, using the os.environ.get()
method is a safer approach. If the environment variable that the program needs to obtain may not exist, the os.environ.get()
method should be used, and a default value should be set to replace the non-existent environment variable value. If it is certain that the environment variable must exist, os.environ['name']
can be used to directly obtain the value of that environment variable.
In the operating system, environment variables are special variables used to store configuration information related to the operating system and applications. In fact, many system information governed by the operating system can be set and obtained through environment variables.
In Python, os.environ stores system environment variables in the form of a dictionary. Each key-value pair represents an environment variable and its corresponding value. You can access and modify the value of environment variables using dictionary-like methods.
For example, you can use os.environ['HOME']
to get the home directory path of the current user, and use os.environ['PATH']
to get the list of executable program paths of the current system, and so on. Using os.environ
can conveniently obtain and set system environment variables, which is one of the commonly used ways to manipulate environment variables in Python programs. However, it should be noted that if you want to get the value of an environment variable, it is usually recommended to use the os.environ.get()
method to avoid the program throwing an exception and stopping running due to non-existent environment variables. If it is certain that the environment variable must exist, os.environ['name']
can be used to directly obtain the value of that environment variable.
end