Environment variables in Python are configuration values stored outside the code and used by the application at runtime. These variables exist as key-value pairs, just like dictionaries in Python. These variables can be set, updated, or deleted in the configuration file without changing the application code. Python provides a number of operating system functions to access environment variables without affecting the application code. In this article, we will learn how to access environment variables in Python.
To interact with the operating system, python has an os module with the help of which you can interact with the operating system and access environment variables. os.environ The dictionary contains all environment variables in key-value pairs.
We can use os.environ to access the path to the environment variable as well as any new environment variable values.
import os # get the value of the PATH environment variable path = os.environ['PATH'] print(path) # set a new environment variable os.environ['MY_VAR'] = 'my value' # get the value of the new environment variable my_var = os.environ['MY_VAR'] print(my_var)
/opt/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/tools/node/bin:/tools/google-cloud-sdk/bin my value
If the environment variable is not found, the code raises a critical error. To avoid such errors, we can use the os.environ.get() function to access environment variables and avoid key errors when the key is not found.
import os # get the value of the MY_VAR environment variable, or return None my_var = os.environ.get('MY_VAR') print(my_var)
None
In the industry, we use different environments for development, staging, and production code bases. There is a separate environment variable file for each environment. Dotenv is a third-party library for accessing environment variables in multiple environments.
To use the dotenv module, we must first install python-dotenv through the following command
pip install python-dotenv
Pip is a python package manager. Pip install python-dotenv Installs the dotenv module into the local file system.
After installing the python-dotenv module, we must create a .env file in the root directory of the project and create environment values in it as key-value pairs.
MY_KEY_VAR=my_value
My_KEY_VAR is the key of the environment variable, and my_value is the corresponding value.
Now, we can load the .env file into our Python code wherever needed using the dotenv.load_dotenv() function, which reads the .env file and loads all environment variables into in the os.environ module.
from dotenv import load_dotenv import os # load the environment variables from the .env file load_dotenv() # get the value of the MY_VAR environment variable my_var = os.environ['MY_KEY_VAR'] print(my_var)
my_value
argparse is a standard library in Python for parsing command line arguments. We can pass environment variables as command line arguments in Python using the argparse library.
Define a command line parameter for each environment variable we want to pass.
Then use the args object returned by argparse to access the environment variables.
Pass environment variables and their values when running the file.
import argparse parser = argparse.ArgumentParser() parser.add_argument('--my-var') args = parser.parse_args() my_var = args.my_var print(my_var)
None
When running the above file, we need to pass the environment value through the key name.
python script.py --my-var "my value"
When we pass the –my-var option and its value "my value" on the command line, the parse_args() method of the argparse module parses the option and gets its value, i.e. "my_value".
Configuration Parser is a Python library for reading configuration files in Python applications.
To use the configure parser module we must
Create a configuration file and declare environment variables as needed in the form of key-value pairs for each part (such as development, production, and staging).
Use the os.getenv() function in the Python file to access the current environment.
In Python files that need to access environment variables, we can use the ConfigParser module to access the environment variables of the current environment.
[development] MY_VAR=my value [production] MY_VAR=another value import configparser import os # get the current environment env = os.getenv('ENVIRONMENT', 'development') # read the configuration file config = configparser.ConfigParser() config.read('config.ini') # get the value of the MY_VAR environment variable for the current environment my_var = config.get(env, 'MY_VAR') print(my_var)
In this article, we explored different ways to access environment variables in Python files. We learned how to use the os module to access environment variables, how to use the dotenv library to access environment variables in multiple environments, how to use the argparse module to pass environment variables as Command line parameter passing, and how to use the ConfigParser module to access the current environment's environment variables from multiple environments.
The above is the detailed content of Access the value of environment variables in Python. For more information, please follow other related articles on the PHP Chinese website!