How to set environment variables in Python?
In Python, setting environment variables can be achieved by using the os module. Below are some common methods for setting environment variables.
- The environment variable in the operating system.
- The route or course that one takes to get from one point to another.
- The directory containing executable files.
import os
os.environ['PATH'] = '/usr/local/bin'
- set an environment variable using os module
- Route
- the directory location of /usr/local/bin
import os
os.putenv('PATH', '/usr/local/bin')
Please note that the os.putenv() function may not work properly on Windows systems.
- dotenv for Python
- configuration file for environment variables
- the environment variables
from dotenv import load_dotenv
import os
load_dotenv('.env')
Please make sure to place the .env file in the same directory as your Python script.
Please note that the environment variables set are only effective in the current Python process and do not have any impact on other processes or system-wide environment variables. To permanently set an environment variable in the terminal, you need to follow the appropriate procedures depending on the operating system you are using.