Setting and Reading Environment Variables in Python
When configuring scripts, it becomes necessary to modify environment variables to provide specific settings for the execution environment. This article discusses setting and accessing these variables in Python.
Setting Environment Variables
Python provides the os.environ dictionary to manage environment variables. To set a variable, simply assign it a string value, as demonstrated below:
import os os.environ["DEBUSSY"] = "1"
Note that the variable name and value must be strings. If a non-string value, such as an integer (1), is assigned, Python will raise an error.
Reading Environment Variables
To access a previously set variable, use the os.environ dictionary with the variable name as the key. For example, to print the value of DEBUSSY:
print(os.environ["DEBUSSY"])
Inheriting Environment Variables
Child processes created with os.fork() or os.spawn() automatically inherit the environment variables of the parent process. This allows the child processes to access the variables set in the parent script.
The above is the detailed content of How Can I Set and Read Environment Variables in Python?. For more information, please follow other related articles on the PHP Chinese website!