Home >Backend Development >Python Tutorial >How Do I Set and Access Environment Variables in Python?
In Python, you may encounter a scenario where you need to declare environment variables for availability to other scripts invoked within your program. Setting these variables is crucial for sharing preferences or custom configurations across multiple executables.
To set an environment variable, you can utilize the os.environ dictionary. However, remember that environment variables must be strings. If you attempt to assign a non-string value, you will encounter an error. The correct syntax to declare a variable DEBUSSY as the value 1 would be:
import os os.environ["DEBUSSY"] = "1"
This assigns the variable DEBUSSY with the string value "1".
Once the variable is set, you can retrieve its value later in the script or in other scripts invoked by your program. To read the environment variable, use:
print(os.environ["DEBUSSY"])
Child processes automatically inherit the environment of their parent process. This means that any variables declared in your Python script will be accessible to scripts launched from it without any additional configuration.
The above is the detailed content of How Do I Set and Access Environment Variables in Python?. For more information, please follow other related articles on the PHP Chinese website!