os.environ
in Python is a mapping object that represents the user’s OS environmental variables. It returns a dictionary having the user’s environmental variable as key and their values as value.
os.environ
behaves like a Python dictionary, so all the common dictionary operations like get and set can be performed. We can also modify os.environ
but any changes will be effective only for the current process where it was assigned and it will not change the value permanently.
os.environ Object Syntax in Python
Syntax: os.environ
Parameter: It is a non-callable object. Hence, no parameter is required
Return Type: This returns a dictionary representing the user’s environmental variables
Python os.environ Object Examples
Below are some examples by which we can fetch environment variables with os.environ in Python and set an environment variable using the OS module in Python:
Access User Environment Variables Using os.environ Object
In this example, the below code uses the `os.environ` object to retrieve and print the list of user’s environment variables, employing the `pprint` module to display them in a readable format.
Python
# importing os module import os import pprint # Get the list of user's env_var = os.environ # Print the list of user's print("User's Environment variable:") pprint.pprint(dict(env_var), width = 1)
Output:
{'CLUTTER_IM_MODULE': 'xim',
'COLORTERM': 'truecolor',
'DBUS_SESSION_BUS_ADDRESS': 'unix:path=/run/user/1000/bus',
'DESKTOP_SESSION': 'ubuntu',
'DISPLAY': ':0',
'GDMSESSION': 'ubuntu',
'GJS_DEBUG_OUTPUT': 'stderr',
'GJS_DEBUG_TOPICS': 'JS '
'ERROR;JS '
'LOG',
'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated',
'GNOME_SHELL_SESSION_MODE': 'ubuntu',
'GTK_IM_MODULE': 'ibus',
'HOME': '/home/ihritik',
'IM_CONFIG_PHASE': '2',
'JAVA_HOME': '/opt/jdk-10.0.1',
'JOURNAL_STREAM': '9:28586',
'JRE_HOME': '/opt/jdk-10.0.1/jre',
'LANG': 'en_IN',
'LANGUAGE': 'en_IN:en',
'LESSCLOSE': '/usr/bin/lesspipe '
'%s '
'%s',
'LESSOPEN': '| '
'/usr/bin/lesspipe '
'%s',
'LOGNAME': 'ihritik',
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:
/usr/local/games:/snap/bin:/usr/local/java/jdk-10.0.1/bin:
/usr/local/java/jdk-10.0.1/jre/bin:/opt/jdk-10.0.1/bin:/opt/jdk-10.0.1/jre/bin',
'PWD': '/home/ihritik',
'QT4_IM_MODULE': 'xim',
'QT_IM_MODULE': 'ibus',
'SESSION_MANAGER': 'local/hritik:@/tmp/.ICE-unix/1127, unix/hritik:/tmp/.ICE-unix/1127',
'SHELL': '/bin/bash',
'SHLVL': '2',
'SSH_AUTH_SOCK': '/run/user/1000/keyring/ssh',
'TERM': 'xterm-256color',
'TEXTDOMAIN': 'im-config',
'TEXTDOMAINDIR': '/usr/share/locale/',
'USER': 'ihritik',
'USERNAME': 'ihritik',
'VTE_VERSION': '4804',
'WAYLAND_DISPLAY': 'wayland-0',
'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/etc/xdg',
'XDG_CURRENT_DESKTOP': 'ubuntu:GNOME',
'XDG_MENU_PREFIX': 'gnome-',
'XDG_RUNTIME_DIR': '/run/user/1000',
'XDG_SEAT': 'seat0',
'XDG_SESSION_DESKTOP': 'ubuntu',
'XDG_SESSION_ID': '2',
'XDG_SESSION_TYPE': 'wayland',
'XDG_VTNR': '2',
'XMODIFIERS': '@im=ibus',
'_': '/usr/bin/python3'}
Retrieving Specific Environment Variables Using os.environ Object
In this example, this code uses the os.environ
object to retrieve and print the values of specific environment variables (‘HOME’ and ‘JAVA_HOME’). It demonstrates accessing the values directly using square bracket notation for an existing variable (‘HOME’) and using the os.environ.get()
method for a variable that may not exist (‘JAVA_HOME’).
Python
# importing os module import os # 'HOME' environment variable home = os.environ['HOME'] print("HOME:", home) # 'JAVA_HOME' environment variable java_home = os.environ.get('JAVA_HOME') # 'JAVA_HOME' environment variable print("JAVA_HOME:", java_home)
Output:
HOME: /home/ihritik
JAVA_HOME: /opt/jdk-10.0.1
Set an Environment Variable Using the OS Module
In this example, the Python code prints the current value of the ‘JAVA_HOME’ environment variable using `os.environ[‘JAVA_HOME’]`, then modifies the value of ‘JAVA_HOME’ to ‘/home/ihritik/jdk-10.0.1’, and prints the modified value using the same method.
Python
# importing os module import os # Print the value print("JAVA_HOME:", os.environ['JAVA_HOME']) # Modify the value os.environ['JAVA_HOME'] = '/home / ihritik / jdk-10.0.1' # Print the modified value print("Modified JAVA_HOME:", os.environ['JAVA_HOME'])
Output:
JAVA_HOME: /opt/jdk-10.0.1
Modified JAVA_HOME: /home/ihritik/jdk-10.0.1
Add New Environment Variable Using os.environ Object
In this example, the Python code uses the `os.environ` object to add a new environment variable named ‘GeeksForGeeks’ with the value ‘www.geeksforgeeks.org’. It then retrieves and prints the value of the added environment variable using os.environ[‘GeeksForGeeks’].
Python
# importing os module import os # Add a new environment variable os.environ['GeeksForGeeks'] = 'www.geeksforgeeks.org' # Get the value print("GeeksForGeeks:", os.environ['GeeksForGeeks'])
Output:
GeeksForGeeks: www.geeksforgeeks.org
Access Environment Variable that Does Not Exists
In this example, the Python code attempts to print the value of the ‘MY_HOME’ environment variable using os.environ['MY_HOME']
. However, there is a syntax error in the code due to the missing closing parenthesis in the print
statement, which would result in a SyntaxError
.
Python
# importing os module import os # Print the value print("MY_HOME:", os.environ.get('MY_HOME', '/home'))
Output:
Traceback (most recent call last):
File "osenviron.py", line 8, in
print("MY_HOME:", os.environ['MY_HOME'])
File "/usr/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'MY_HOME'
Handling Error while Access Environment Variable which Does Not Exists
In this example, the code demonstrates two methods to access the value of the environment variable ‘MY_HOME.’ The first method uses `os.environ.get()` with a default message if the variable is not found, while the second method uses a try-except block to catch a KeyError if the variable is not present.
Python
# importing os module import os # Method 1 print("MY_HOME:", os.environ.get('MY_HOME', "Environment variable does not exist")) # Method 2 try: print("MY_HOME:", os.environ['MY_HOME']) except KeyError: print("Environment variable does not exist")
Output:
MY_HOME: Environment variable does not exist
Environment variable does not exist
Пройдите тест, узнайте какой профессии подходите
Переменные окружения — это глобальные значения, которые хранят различные данные на вашем компьютере. Они доступны для всех программ и могут быть
Переменные окружения — это глобальные значения, которые хранят различные данные на вашем компьютере. Они доступны для всех программ и могут быть использованы для передачи информации между программами или для контроля поведения программ.
В Python для работы с переменными окружения используется модуль os
. Он предоставляет функциональность для взаимодействия с операционной системой, включая переменные окружения.
Освойте Python на курсе от Skypro. Вас ждут 400 часов обучения и практики (достаточно десяти часов в неделю), подготовка проектов для портфолио, индивидуальная проверка домашних заданий и помощь опытных наставников. Получится, даже если у вас нет опыта в IT.
Установка переменных окружения
Для установки значения переменной окружения в Python используется метод os.environ
. Это словарь, который содержит текущие переменные окружения. Для установки нового значения достаточно просто присвоить его ключу этого словаря.
Пример:
import os os.environ["MY_VARIABLE"] = "my value"
Важно отметить, что все значения переменных окружения должны быть строками. Если попытаться присвоить другой тип данных, Python выдаст ошибку. Например, следующий код вызовет ошибку:
os.environ["MY_VARIABLE"] = 1 # Неверно!
Для того чтобы присвоить числовое значение, его нужно сначала преобразовать в строку:
os.environ["MY_VARIABLE"] = str(1) # Верно
Чтение переменных окружения
Для чтения значения переменной окружения также используется os.environ
. Просто обратитесь к нужному ключу, как если бы это был обычный словарь:
value = os.environ["MY_VARIABLE"]
Если переменная окружения не существует, Python выдаст ошибку. Чтобы избежать этого, можно использовать метод get
, который возвращает None
, если переменная не найдена:
value = os.environ.get("MY_VARIABLE")
В этом случае, если переменная «MY_VARIABLE» не существует, value
будет равно None
.
Изучайте Python на онлайн-курсе от Skypro «Python-разработчик». Программа рассчитана на новичков без опыта программирования и технического образования. Курс проходит в формате записанных коротких видеолекций. Будет много проверочных заданий и мастер-классов. В конце каждой недели — живая встреча с экспертами в разработке для ответов на вопросы и разбора домашек.
Итак, с помощью модуля os
в Python можно легко устанавливать и читать переменные окружения, что позволяет эффективно работать с глобальными настройками и передавать информацию между различными частями программы.
- Introduction
- The os Module
-
Creating Environment Variables
- Method One: Creating Environment Variables Via The Operating System
- Linux and macOS
- Windows
- Method Two: Creating Environment Variables Using Python
-
Getting Environment Variables With The OS Module
- Example One: Working With A String
- Example Two: Working With A Number
- Example Three: Working With A Boolean
- Conclusion
- References
Introduction
Environment variables are used in a program to set the values of variables or constants within that program. The environment variables exist at the operating system level. This allows for the environment variables to be fluid in that they can be changed for different stages of the software development lifecycle without storing / changing the values in the source code for each stage (dev / test / production).
From a security perspective, it means that the source code does not have the values of its variables hard-coded into them. An example of this would be storing an API key as an environment variable instead of setting the value in a variable / constant in the source code. If that happened and was then sent up to a public (or even a private) Git repository, that would be a major security threat.
The os Module
For Python to interact with the operating system, the os
module is used. It can perform actions such as:
- Creating and reading environment variables.
- Getting details about the operating system, such as the type of operating system it is.
- Working with files and file paths.
There are a lot more that it can do, which is covered in the modules documentation.
So how can environment variables be created and used?
Creating Environment Variables
First up, let’s create some environment variables to work with. There are multiple ways to do this, but this article will focus on two. The first of which is to create them via the operating system with the second being via Python using os.environ
.
Three example environment variables will be created, each with a different data type.
For both methods:
- EXAMPLE_ONE is just a string of text. This is a typical use case for most data that would be assigned to an environment variable.
- EXAMPLE_TWO is a number. Or is it? More on that later.
- EXAMPLE_THREE is a boolean. Or perhaps not. Again, more on that later.
Method One: Creating Environment Variables Via The Operating System
NOTE: On Linux / macOS, if the string has spaces in it, the string will need to be wrapped in ""
, otherwise only the text up to the first space will be assigned. Windows is fine without them.
Linux and macOS
Using a terminal emulator app, run:
export EXAMPLE_ONE="This is an environment variable"
export EXAMPLE_TWO=1
export EXAMPLE_THREE=False
Enter fullscreen mode
Exit fullscreen mode
If an environment variable needs to be persistent for Linux or macOS, it will need to be added to the users .bashrc
or .zshrc
file in their home directory using the same syntax.
Windows
Using the command prompt (cmd.exe), run:
set EXAMPLE_ONE=This is an environment variable
set EXAMPLE_TWO=1
set EXAMPLE_THREE=False
Enter fullscreen mode
Exit fullscreen mode
To set persistent environment variables in Windows, use the setx
command with the syntax being:
setx EXAMPLE_ONE "This is an environment variable"
setx EXAMPLE_TWO "1"
setx EXAMPLE_THREE "False"
Enter fullscreen mode
Exit fullscreen mode
Method Two: Creating Environment Variables Using Python
For all three operating system types, the method is the same in Python by using os.environ
:
import os
os.environ["EXAMPLE_ONE"] = "This is an environment variable"
os.environ["EXAMPLE_TWO"] = "1"
os.environ["EXAMPLE_THREE"] = "False"
Enter fullscreen mode
Exit fullscreen mode
NOTE: When Python is closed, these environment variables will be removed.
Getting Environment Variables With The OS Module
There are two methods that can be used to access an environment variable using the os
module. The first method is via os.environ
. It requires the environment variable name to be passed to it in a list. For example:
import os
print(os.environ["EXAMPLE_ONE"])
Enter fullscreen mode
Exit fullscreen mode
Output:
This is an environment variable
Enter fullscreen mode
Exit fullscreen mode
There is one downside to this method, which is open to interpretation. If the environment variable is not present, it will raise a KeyError
and cause a hard stop. An example of this is shown below:
Traceback (most recent call last):
File "/Users/neil/Documents/writing/blog-posts/code.py", line 11, in <module>
print(os.environ["EXAMPLE_ONE"])
~~~~~~~~~~^^^^^^^^^^^^^^^
File "<frozen os>", line 679, in __getitem__
KeyError: 'EXAMPLE_ONE'
Enter fullscreen mode
Exit fullscreen mode
Now, this might be what is required to happen, which is fine. But let’s say that it isn’t and the code needs to continue. To get around this, os.getenv
is a useful solution. What this will do is instead of erroring out, it will set the value to None
for any missing environment variables instead.
For the examples going forward, the os.getenv
method will be used.
Example One: Working With A String
The first example will get the value or the EXAMPLE_ONE
environment variable and show its value.
import os
example_one = os.getenv("EXAMPLE_ONE")
print(f"Example One Value: {example_one}")
print(type(example_one))
Enter fullscreen mode
Exit fullscreen mode
Output:
Example One Value: This is an environment variable
<class 'str'>
Enter fullscreen mode
Exit fullscreen mode
From the output, the value of example_one
is shown and it has a data type of str
(string).
Example Two: Working With A Number
This is where things get problematic. Remember how Example Two was described earlier («EXAMPLE_TWO is a number. Or is it?»). Well, although it looks like a number, it is actually a string data type. This is because environment variables are treated as strings, no matter what the value is.
For example, let’s access the EXAMPLE_TWO
environment variable and see what data type it has:
import os
example_two = os.getenv("EXAMPLE_TWO")
print(f"Example Two Value: {example_two}")
print(type(example_two))
Enter fullscreen mode
Exit fullscreen mode
Output:
Example Two Value: 1
<class 'str'>
Enter fullscreen mode
Exit fullscreen mode
As can be seen, the data type class is str
(string). So how can the value be used as a number, in this case an integer? It is done by enforcing the data type to the example_two
variable using the int
class. For example:
import os
example_two = int(os.getenv("EXAMPLE_TWO"))
print(f"Example Two Value: {example_two}")
print(type(example_two_int))
Enter fullscreen mode
Exit fullscreen mode
Output:
Example Two Value: 1
<class 'int'>
Enter fullscreen mode
Exit fullscreen mode
The output looks the same but the data type for example_two
is now an integer (int). This will now allow it to be used for any mathematical operations.
There is one further issue. What if the environment variable is not an integer number but rather a string, float, boolean or just doesn’t exist?
If it doesn’t exist, the value would be set to None
. If it did exist and is not an integer, it would be set to that value. But, as the data type is enforced as an integer, a ValueError
would be raised for both cases.
A solution for this would be to use the try
block to check it.
The following example will check the value of EXAMPLE_TWO
and if it can’t be set to an integer data type due to the value not being an integer, it will set example_two
to 0
:
First, change EXAMPLE_TWO
to a non-number-based value:
Operating system method:
export EXAMPLE_TWO="I am not a number"
Enter fullscreen mode
Exit fullscreen mode
Or via Python:
import os
os.environ["EXAMPLE_TWO"] = "I am not a number"
Enter fullscreen mode
Exit fullscreen mode
Next, use the try
block to check and set the value of example_two
:
import os
try:
example_two_int = int(os.getenv("EXAMPLE_TWO"))
except ValueError:
example_two_int = 0
print(f"Example Two Value: {example_two_int}")
print(type(example_two_int))
Enter fullscreen mode
Exit fullscreen mode
Output:
Example Two Value: 0
<class 'int'>
Enter fullscreen mode
Exit fullscreen mode
As EXAMPLE_TWO
was not a numeric value, a ValueError
was raised and as a result, the value of example_two
was set to 0
.
Example Three: Working With A Boolean
Just as in example two, an environment variable with what looks like a boolean value will have a string data type. This will mean that it cannot be used for boolean operations.
One of the additional issues with boolean values is how they can be presented. For example, in Python a boolean value is set to either True
or False
. In other languages, such as JavaScript, they are set to either true
or false
. There are others, such as yes / no, y / n, 0 / 1 or on / off.
So, how can we set a boolean data type when there are a lot of possible ways that an environment variable can be set with a boolean value? This is actually easy to do with Python. Start by putting as many of the possible ways to present a True
value in a list and compare the value that is assigned to the environment variable. If the value matches one of the entries in the list, the value of the variable will be set to True
. If not, it will be False
.
For example, set a False
boolean value:
import os
example_three = os.getenv("EXAMPLE_THREE") # --- Currently set to "False"
example_three = example_three.lower() in ["true", "1", "1.0", "y", "yes", "on"]
print(f"Example Three Value: {example_three}")
print(type(example_three))
Enter fullscreen mode
Exit fullscreen mode
Output:
Example Three Value: False
<class 'bool'>
Enter fullscreen mode
Exit fullscreen mode
In the above example, the value of example_three
was converted to all lowercase to make it easier to check against and then compared to each entry in the list. As it didn’t match, the new value of example_three
is False
but with a data type class of bool
, which is what is needed.
Conclusion
I hope that this article was useful. There will be a follow up article to this that will cover using .env files for creating environment variables.
Thank you for reading and have a nice day!
References
Python os module documentation.
Setting environment variables in Python is an essential skill for developers, allowing them to manage and streamline the configuration of their applications.
You’re able to set, store and easily modify these variables without altering the application’s core functionality.
You can set environment variables in Python using the os module, which provides a simple interface for working them. By using this module, developers can quickly set and get environment variables, making their programs more versatile and ideally suited to changing development or production environments.
Throughout this article, we’ll discuss effective techniques for setting and accessing environment variables within your Python code and leveraging their potential to produce cleaner, more flexible applications.
From using the os module to various command line tools, this guide will provide valuable insights to streamline your development process and promote best practices across your projects.
Let’s dive in!
What is an Environment Variable?
Environment variables are variables set outside the program in its running environment by the user, operating system (OS), etc.
They are key-value pairs used by operating systems to store information about the environment, such as paths and configuration settings.
Some common environment variables related to Python include PATH, PYTHONPATH, and PYTHONHOME.
Other use cases include API keys, database credentials, and other sensitive information stored outside of the code to enhance security and maintainability.
For example, if we’re pulling data from an API like the GoogleNews API in our video below, we can use environment variables to store the API keys.
By doing this, we avoid hardcoding the keys.
Scope of Environment Variables
There are two types of environment variables: system variables and user variables. System variables are globally accessible for all users, while user environment variables are only accessible to the specific user account.
For example, the PATH variable is one of the critical system environment variables that determine the directories where the OS searches for executables, like the Python interpreter.
To effectively work with Python, it’s essential to add the interpreter’s location to the PATH environment variable.
This allows you to run Python commands from the command line without specifying the full path to the Python executable. You can typically add Python to the PATH when installing it, or you can manually modify it later.
How to Set Environment Variables in Python
There are two methods you can use in setting environment variables in Python. You can either use the OS module or the python-dotenv library.
Let’s look at how they work:
1. How to Set Environment Variables Using the OS Module
The OS module in Python provides a convenient and portable way to interact with the operating system. The os.environ dictionary is an essential part of this module, as it allows Python programs to access and modify environment variables.
It represents the environment variables of the operating system. We can use this dictionary to get, set, and modify environment variables in Python.
Let’s take a look at how it works:
1. Setting Environment Variables
To set an environment variable, you can assign a value to a specific key in the os.environ dictionary. Make sure that the value is always a string. Here’s an example:
import os
os.environ['MY_VARIABLE'] = 'hello'
You can also use it to modify the value of an existing environment variable.
2. Retrieving Environment Variables
To retrieve environment variables, you can use the os.environ dictionary as a regular Python dictionary. To get the value of a specific environment variable, simply use the variable’s name as the key.
For example:
import os
home_dir = os.environ['HOME']
If the environment variable exists, it returns its value. If it doesn’t, it returns a KeyError exception.
Alternatively, you can use the os.getenv() and os.environ.get() methods to access environment variables, avoiding a KeyError when the variable does not exist:
#Both of these environment varaibles don't exist.
user = os.getenv('API_USER')
password = os.environ.get('API_PASSWORD', 'default value')
Output:
None
default value
They return None if the variable doesn’t exist. You can also set a default value as the second argument in both functions if the environment variable doesn’t exist.
Remember that the OS module is an important tool for managing environment variables in Python programs. By using the os.environ dictionary to set and get variables, you can confidently interact with the operating system in a portable and clear manner.
2. How to Set Environment Variables Using the Dotenv Package
The Python-dotenv package is a valuable tool that can help you manage environment variables in your Python applications. It allows you to store key-value pairs in a .env file, keeping sensitive information separate from your application code and preventing accidental leaks or hard-coding of variables.
Also, setting multiple environment variables with the os.environ library can take quite a bit of time. By using a .env file, you can load multiple environment variables into your running environment immediately after your program starts running.
Let’s look at how you can use it:
1. Loading Environment Variables with Load_Dotenv
To begin, ensure that the Python-dotenv package has been installed. If you haven’t done so already, you can install it using the pip install python-dotenv command on your terminal.
Once installed, you can import the load_dotenv function from the package and use it to load the key-value pairs from your .env file as environment variables. These variables can then be accessed using Python’s os module.
Here’s a brief example:
from dotenv import load_dotenv
import os
load_dotenv()
access_token = os.getenv("ACCESS_TOKEN")
secret_token = os.getenv("SECRET_TOKEN")
In this example, the .env file should be located in your project directory and should contain the key-value pairs for ACCESS_TOKEN and SECRET_TOKEN.
Note: When using environment variables in your Python project, it’s important to keep security in mind. Since the .env file may contain sensitive information, such as API keys or secrets, it is essential that you exclude it from version control systems such as Git.
To do this, simply add the .env file to your .gitignore file:
# .gitignore
.env
By doing so, you ensure that the .env file is not accidentally committed to your Git repository, keeping your sensitive data secure. You can read more about this module in our article on Python-Dotenv: Setting Environmental Variables.
How to Set Environment Variables via the Command Line
You can set environment variables for your program directly from your command line interface. This method provides an alternative to setting environment variables via Python.
You can also use them to set permanent environment variables system-wide. Here’s how you can achieve this in various operating systems:
1. How to Set Environment Variables in Windows
In Windows, you can set environment variables permanently using the setx command in the Command Prompt. Here’s an example of setting the PYTHONPATH:
setx PYTHONPATH "C:\path\to\your\python\directory"
This will make the PYTHONPATH environment variable permanent. To temporarily set an environment variable, use the set command:
set PYTHONPATH=C:\path\to\your\python\directory
Alternatively, you can set environment variables through the System Properties window, under “Environment Variables.“
After setting the environment variable, you can retrieve them using the echo %<variable-name>% format. For example:
set PYTHONPATH=C:\path\to\your\python\directory
echo %PYTHONPATH%
Output:
To list all environment variables, you can simply run the set command in the terminal.
2. How to Set Environment Variables in Unix (Linux & macOS)
In Unix-based operating systems such as Linux and MacOS, the export command is used to set environment variables. Here’s an example of setting the PYTHONPATH:
export PYTHONPATH="/path/to/your/python/directory"
This will set the environment variable for the current session. Once you terminate the shell, the environment variable will be deleted. To make it permanent, you can add the export command to your shell configuration file (e.g., .bashrc, .zshrc, or .profile).
To get the value of an environment variable, use the echo command:
echo $PYTHONPATH
To list all the environment variables, you can use the printenv command.
What is the Scope of an Environment Variable in Python?
In Python, environment variables’ scope is limited to the process they belong to and any subprocesses spawned by the parent process.
When you modify an environment variable within a Python script, its changes only affect the current process and the spawned subprocesses, but not the calling process or the entire system.
For example, you can temporarily modify the current process’s environment using Python’s os module:
import os
# Store initial PATH value
initial_path = os.environ['PATH']
# Set a new PATH value for the process
os.environ['PATH'] = '/new/directory:' + initial_path
# Perform actions using the updated PATH
# Restore initial PATH value
os.environ['PATH'] = initial_path
It’s important to note that modifying environment variables within a Python script will not change the overall system or user environment permanently.
This temporary modification mainly helps in managing dependencies and enabling specific behaviors for sub-processes, such as changing the Python startup behavior or configuration.
Advanced Environment Management in Python
Having navigated the foundational concepts of environment management in Python, you’ve established a strong footing in ensuring project consistency and avoiding dependency conflicts.
However, as we venture into more intricate and large-scale projects, a deeper understanding becomes paramount. This section builds upon that foundation, diving into the nuances and sophisticated techniques that cater to the multifaceted demands of complex Python endeavors.
1. Handling Newlines in Environment Variables
When working with environment variables in Python, you might encounter issues with newline characters. Newlines can cause unexpected behavior, especially when passing environment variables to subprocesses. Therefore, it’s essential to handle them correctly.
You can remove newlines using the str.strip() function:
import os
raw_value = os.environ.get("MY_VARIABLE", "")
clean_value = raw_value.strip()
2. Default Values in Python Code
It’s common to use default values for environment variables in case they aren’t set in the system environment. This can be done using the os.environ.get() method or the os.getenv() function:
import os
# Using os.environ.get()
default_value = "default"
my_var = os.environ.get("MY_VAR", default_value)
# Using os.getenv()
another_var = os.getenv("ANOTHER_VAR", default_value)
Both methods retrieve the value of the environment variable if it exists, else return the specified default value.
3. Working with Child Processes
When creating subprocesses in Python, you might need to pass environment variables to them. The subprocess module provides an easy way to do this:
import os
import subprocess
# Set environment variables
os.environ["API_USER"] = "username"
os.environ["API_PASSWORD"] = "secret"
# Pass environment to child process
env = os.environ.copy()
result = subprocess.run(["your_command"], env=env)
In the above example, the os.environ.copy() function is used to create a copy of the current environment, which is then passed to the child process.
This method enables the child process to inherit the environment variables from the parent process while avoiding inadvertent changes to the global system environment.
Final Thoughts
The importance of configuring environment variables in Python can’t be overstated. Through the utilization of the os and python-dotenv modules, this process remains both accessible and efficient.
In a digital landscape where adaptability is key, Python’s elegant approach to managing environment variables underscores its position as a language of choice for pragmatic and effective programming.
That’s the end of our article on environment variables in Python. If you enjoyed be sure to read through our article on How to Delete Files from Python: 6 Easy Methods Explained.
Frequently Asked Questions
What is the proper way to set environment variables permanently in Linux?
In Linux, you can set environment variables permanently by adding export statements to the ~/.bashrc or ~/.profile file. Open the file with a text editor and append the following line:
export MY_VARIABLE=my_value
Save and exit the file. To apply the changes, either restart the terminal or use the command source ~/.bashrc or source ~/.profile.
What is the method to print all environment variables in Python?
To print all environment variables in Python, you can iterate through the os.environ dictionary after importing the os module:
import os
for key, value in os.environ.items():
print(f"{key}: {value}")
Do Python environment variables work in a virtual environment?
Yes, environment variables in Python work can work in a virtual environment. You can access and set them in the same way as in a regular environment.
You can even add the environment variable into the virtual environment’s activate.bat file for easy loading. This way, every time you load up the virtual environment, the program sets the environment variable.
You can append the export statement at the bottom of the script. For example:
export KEY = VALUE
Are environment variables set with Python?
No, environment variables set with Python are not permanent. They do not persist outside of the Python process.
Once the script or shell stops running, the environment variables are deleted or reverted to the system defaults.
В статье рассказывается:
В статье рассказывается:
- Определение переменных окружения в Python
- Виды переменных окружения Python
- Работа с переменными окружения Python
- Работа с библиотекой python-dotenv
-
Пройди тест и узнай, какая сфера тебе подходит:
айти, дизайн или маркетинг.Бесплатно от Geekbrains
Переменные окружения Python необходимы для изменения настроек системы. Кроме этого, многие программы, написанные на данном языке, корректно работают только при правильном значении переменных среды. Если эти значения изменятся, скрипт перестанет работать задуманным образом, и его нужно будет отладить.
Не менее значимая функция переменных окружения – это использование их для хранения закрытых данных, таких как токены, пароли, IP-ключи и т. д. В нашем материале мы расскажем более подробно о задачах переменных среды и покажем, как с ними можно работать.
Переменная, чье значение присваивается Python извне, называют переменной окружения. Как правило, ее устанавливают в командной строке перед тем, как обратиться к исполняемому файлу Python. После этого ОС позволяет программе Python получать доступ к такой переменной.
Переменные окружения в Python необходимы для гибкости программы. Благодаря им, пользователь получает возможность менять нужные параметры перед выполнением программы. Программа же, в свою очередь, может просматривать изменяемые параметры, динамически подстраивая свое поведение. Т.е. нет необходимости модифицировать код. Такое применение переменных окружения будет называться настройкой программы.
Алгоритм, по которому проходит установка переменных окружения, напрямую зависит от платформы. Поэтому следует использовать встроенный модуль OS компании Python для считывания переменных. Функции этого модуля позволяют взаимодействовать с операционной системой вне зависимости от ее платформы.
Для доступа к таким переменным в Python используется объект os.environ — это словарь, в котором хранятся все переменные окружения программы.
Читайте также!
Frontend-разработчик: навыки, зарплата, обучение
Имейте в виду, что объект os.environ фиксируется при загрузке модуля OS на Python. И если вы будете изменять переменные окружения после этого, то изменения не отобразятся os.environ (например, при экспорте новой переменной окружения в терминальный эмулятор).
Виды переменных окружения Python
- PYTHONHOME
Меняет местоположение стандартных библиотек Python. Изначально они находятся в prefix/lib/pythonversion и exec_prefix/lib/pythonversion, где prefix и exec_prefix — каталоги, которые зависят от установки, оба по умолчанию — /usr/local.
Если для этой переменной окружения задан один каталог, то его значение может заменить prefix или exec_prefix. Для указания разных значений установите PYTHONHOME на prefix:exec_prefix.
- PYTHONPATH
По умолчанию изменяет путь поиска для файлов модулей. Имеет такой же формат, как и для оболочки PATH — т. е. один или более путей каталога, разделяемых os.pathsep (например, знак «:» в Unix или «;» в Windows). Происходит автоматическое игнорирование несуществующих каталогов.
Дополнительный каталог указывается в пути поиска перед PYTHONPATH, как было рассмотрено выше в пункте «Интерфейсные опции». При необходимости изменения пути поиска нужно обратиться к переменной sys.path в программе Python.
Топ-30 самых востребованных и высокооплачиваемых профессий 2023
Поможет разобраться в актуальной ситуации на рынке труда
Подборка 50+ бесплатных нейросетей для упрощения работы и увеличения заработка
Только проверенные нейросети с доступом из России и свободным использованием
ТОП-100 площадок для поиска работы от GeekBrains
Список проверенных ресурсов реальных вакансий с доходом от 210 000 ₽
Уже скачали 34220
- PYTHONSTARTUP
Если эта переменная является именем файла, то Python-команды в этом файле будут выполняться до первого приглашения в интерактивном режиме. Файл и интерактивные команды выполняются в одном пространстве имен. Поэтому и определенные, и импортированные в этом пространстве объекты могут быть использованы без квалификации в интерактивном сеансе. Также можно изменять подсказки в этом файле sys.ps1 и sys.ps2 и хук sys.__interactivehook__.
- PYTHONOPTIMIZE
Если в этой переменной окружения задана непустая строка, то это равнозначно указанию параметра -О. Если же задано целое число, то это равносильно -ОО.
- PYTHONBREAKPOINT
Если эта переменная окружения Python установлена, то она определяет вызываемый объект, применяя нотацию пути с точками. Модуль с вызываемым объектом импортируется, далее непосредственно сам вызываемый объект будет запущен реализацией по умолчанию sys.breakpointhook(), вызываемая, в свою очередь, встроенной функцией breakpoint().
Если PYTHONBREAKPOINT не задана или установлена пустая строка, то это равносильно значению «pdb.set_trace». Если установить такое значения в строку «0», то это приведет к действию немедленного возврата со стороны реализации по умолчанию sys.breakpointhook().
- PYTHONDEBUG
Если для этой переменной в качестве значения указана непустая строка, то это равносильно указанию параметра -d. Если же указано целое число, то это равнозначно -dd.
- PYTHONINSPECT
Если значение переменной указано, как пустая строка, то это равносильно значению параметра -i.
Переменную окружения PYTHONINSPECT можно изменить кодом Python с применением os.environ для принудительного проверочного режима по окончанию работы программы.
- PYTHONUNBUFFERED
Если в качестве значения этой переменной окружения Python задана непустая строка, то это равносильно указанию параметра -u.
- PYTHONVERBOSE
Если для нее задается значение непустой строки, то это равнозначно указанию параметра -v. Если устанавливается целое число, то это равнозначно -vv.
- PYTHONCASEOK
При установленном значении этой переменной Python пренебрегает регистром в операторах import. Это будет работать только в OS X и Windows.
- PYTHONDONTWRITEBYTECODE
Если в качестве значения этой переменной установлена непустая строка, то это равнозначно указанию параметра -В. Т.е. Python не станет писать файлы.рус.
- PYTHONPYCACHEPREFIX
Если для переменной значение установлено, то это равносильно указанию параметру -Х pycache_prefix=PATH. Т.е. Python осуществит запись фалов.рус не в каталогах __pycache__ в исходном дереве, а в зеркальном дереве каталогов по этому пути.
Скачать
файл
- PYTHONHASHSEED
В случае, когда значение такой переменной определено, как random, или же она не установлена, то применяется случайное значение для заполнения хэшей объектов.
Если для значения переменной указано целое число, то оно используется, как неизменное начальное число для генерации hash() типов, включенных в процесс рандомизации хэша.
Главной целью является разрешение повторяемого хеширования (например, для самопроверки интерпретатора). А также допуск к совместному использованию хеш-значений кластером процессов Python.
- PYTHONIOENCODING
Если эта переменная окружения установлена до начала запуска интерпретатора, то она заменяет кодировку, которую используют в stdin/stdout/stderr, в синтаксисе encodingname:errorhandler. И encodingname, и :errorhandler являются необязательными и содержат то же значение, что и str.encode().
Stderr пренебрегает частью :errorhandler. Обработчик всегда будет ‘backslashreplace’.
Дарим скидку от 60%
на обучение «Frontend-разработчик» до 18 мая
Уже через 9 месяцев сможете устроиться на работу с доходом от 150 000 рублей
Забронировать скидку
- PYTHONNOUSERSITE
Если значение этой переменной задано, то Python не будет добавлять каталог пользователя site-packages в sys.path.
- PYTHONUSERBASE
Данная переменная задает базовый пользовательский каталог, который применяют при вычислении пути установки Distutils для python setup.py install —user и пути пользовательской директории site-packages.
- PYTHONEXECUTABLE
Если значение этой переменной задано, то для sys.argv[0] будет установлено её значение вместо значения, полученного через среду выполнения C. Работает только в Mac OS X.
Только до 19.05
Скачай подборку материалов, чтобы гарантированно найти работу в IT за 14 дней
Список документов:
ТОП-100 площадок для поиска работы от GeekBrains
20 профессий 2023 года, с доходом от 150 000 рублей
Чек-лист «Как успешно пройти собеседование»
Чтобы получить файл, укажите e-mail:
Введите e-mail, чтобы получить доступ к документам
Подтвердите, что вы не робот,
указав номер телефона:
Введите телефон, чтобы получить доступ к документам
Уже скачали 52300
- PYTHONWARNINGS
Эта переменная равнозначна опции -W. Если значение указано в виде строки, разделенной запятыми, то это равносильно многократному указанию -W. При этом фильтры, которые были расположены в списке позже, будут иметь преимущество над фильтрами, расположенными в списке ранее.
- PYTHONFAULTHANDLER
В случае, когда для такой переменной задается непустая строка, то при запуске будет вызван faulthandler.enable(): установить обработчик для сигналов SIGSEGV, SIGFPE, SIGABRT, SIGBUS и SIGILL для дампа трассировки Python. Это равнозначно опции —X faulthandler.
- PYTHONTRACEMALLOC
При определении этой переменной непустой строкой начинается отслеживание выделения памяти Python с использованием модуля tracemalloc. Значением переменной будет являться наибольшее количество фреймов, сохраняемых в обратной трассировке trace.
- PYTHONPROFILEIMPORTTIME
Когда значение этой переменной — непустая строка, то Python укажет количество времени, занимаемое каждым импортом. Это полностью соответствует настройке —X importtime в командной строке.
- PYTHONASYNCIODEBUG
Когда для такой переменной окружения задается непустая строка, то происходит включение режима отладки модуля asyncio.
Читайте также!
Что такое доменное имя: от общего понятия, до регистрации
- PYTHONMALLOC
Эта переменная задает распределители памяти Python и/или устанавливает отладочные хуки.
- PYTHONMALLOCSTATS
При установке непустой строки для этой переменной Python осуществит печать статистики pymalloc распределителя памяти. Причем это будет происходить каждый раз, когда создаётся новая объектная арена pymalloc, а также при завершении работы.
Эта переменная будет проигнорирована, если PYTHONMALLOC применяется для принудительного использования распределителя malloc() библиотеки C, или если Python был настроен без поддержки pymalloc.
- PYTHONLEGACYWINDOWSFSENCODING
Если для значения этой переменной задана непустая строка, то режим ошибок и кодировка файловой системы по умолчанию откатятся до значений в версии 3.6 «replace» и «mbcs» соответственно. В ином случае будут использованы значения по умолчанию «surrogatepass» и «utf-8».
- PYTHONLEGACYWINDOWSSTDIO
При для переменной используется непустая строка, то новые средства чтения и записи консоли не будут применены. Т.е. символы Юникод будут кодироваться согласно активной кодовой странице консоли, а не с использованием utf-8.
Переменная будет проигнорирована, если стандартные потоки перенаправляются (в каналы или файлы), а не ссылаются на буферы консоли.
- PYTHONCOERCECLOCALE
Если в качестве значения переменной указывается «0», то основное приложение командной строки Python будет пропускать приведение устаревших локалей C и POSIX на основе ASCII к более действенной альтернативе на основе UTF-8.
Если значение переменной не установлено (или не равно «0»), то переменная окружения переопределения локали LC_ALL тоже не устанавливается, а текущая локаль, указанная для категории LC_CTYPE, является либо локалью по умолчанию C, либо явно ASCII-основанной локали POSIX, то Python CLI будет пытаться настроить следующие локали для категории LC_CTYPE в порядке, который был указан перед загрузкой среды выполнения интерпретатора.
Для целей отладки установка PYTHONCOERCECLOCALE=warn даст результат, при котором Python будет выдавать предупреждающие сообщения на stderr, если будет активировано принуждение локали, или если языковой стандарт, вызывающий приведение, всё ещё активен при инициализации среды выполнения Python.
- PYTHONDEVMODE
Когда для такой переменной задается непустая строка, то активируется «режим разработки» Python. (См. опцию -X dev)
- PYTHONUTF8
Если для этой переменной задано значение «1», то это активирует режим интерпретатора UTF-8, где UTF-8 применяется, как кодировка текста для интерфейсов системы, независимо от текущей настройки локали.
Если задано значение «0», то интерпретатор будет работать в режиме с учётом локали по умолчанию.
Установка любой другой непустой строки будет вызывать ошибку при инициализации интерпретатора.
Работа с переменными окружения Python
- Считывание одной/всех переменных окружения
Код, указанный ниже, помогает прочесть и вывести одну конкретную или же все переменные окружения. Для того чтобы сделать вывод имен и значений всех переменных, применяют цикл FOR. Далее выводится значение переменной HOME.
# Импортируем модуль os
import os
# Создаём цикл, чтобы вывести все переменные среды
print(«The keys and values of all environment variables:»)
for key in os.environ:
print(key, ‘=>’, os.environ[key])
# Выводим значение одной переменной
print(«The value of HOME is: «, os.environ[‘HOME’])
Если выполнить этот скрипт, то можно увидеть следующее: сначала был получен перечень всех переменных окружения, а потом — значение переменной HOME.
- Проверка присвоения переменной окружения ее значения
Для проверки переменных создадим Python-файл с нижеуказанным скриптом. Модуль OS будем использовать для чтения значений переменных. Модуль SYS – для завершения работы приложения.
Бесконечный цикл while будет без остановки принимать имена переменных от пользователя. Также цикл будет проверять их значения до того момента, как пользователь не введет имя такой переменной, значение для которой не присвоено.
Если пользователь вводит имя переменной окружения с указанным значением, то это значение будет выведено. В противном случае — будет выведено сообщение об ошибке, и процесс прервется.
# Импортируем модуль os
import os
# Импортируем модуль sys
import sys
while True:
# Принимаем имя переменной среды
key_value = input(«Enter the key of the environment variable:»)
# Проверяем, инициализирована ли переменная
try:
if os.environ[key_value]:
print(«The value of», key_value, » is «, os.environ[key_value])
# Если переменной не присвоено значение, то ошибка
except KeyError:
print(key_value, ‘environment variable is not set.’)
# Завершаем процесс выполнения скрипта
sys.exit(1)
Итог работы скрипта можно увидеть на скрине. В первом случае вводилось имя переменной с определенным значением. Во втором — имя переменной с неустановленным значением. Согласно результату, переменная HOME была определена, и ее значение появилось в консоли. Для переменной API_KEY значение не указывалось, поэтому скрипт вывел сообщение и прекратил работу.
- Проверка переменной на истинность
Создадим файл в Python с нижеуказанным кодом. Чтобы проверить переменную DEBUG на истину, используем функцию get(). В соответствии со значениями переменной программа будет выводить различные сообщения.
# Импортируем модуль os
import os
# Проверяем значение переменной среды
if os.environ.get(‘DEBUG’) == ‘True’:
print(‘Debug mode is on’)
else:
print(‘Debug mode is off’)
При значении переменной DEBUG – False, итог работы кода будет соответствовать скрину. Используя функцию setdefault, можно менять значение переменной.
- Наделение переменной окружения значением
Чтобы любой переменной окружения присвоить значение, используют функцию setdefault().
Создадим код, изменяющий значение переменной DEBUG на True (по умолчанию установлено False), применяя функцию setdefault(). После присвоения значения осуществим проверку функцией get().
При верном написании кода появится сообщение «Режим отладки включен». При ошибочном – «Режим отладки выключен».
# Импортируем модуль os
import os
# Задаём значение переменной DEBUG
os.environ.setdefault(‘DEBUG’, ‘True’)
# Проверяем значение переменной
if os.environ.get(‘DEBUG’) == ‘True’:
print(‘Debug mode is on’)
else:
print(‘Debug mode is off’)
На скрине ниже показан результат: переменной DEBUG было задано значение True, поэтому появилось сообщение «Режим отладки включен».
Работа с библиотекой python-dotenv
Пакет python-dotenv предназначен для того, чтобы при новом запуске терминала не тратить время на внесение переменных окружения вручную. Становится возможным загружать их из файла .env в корневом каталоге приложения.
Установим пакет:
pip install python-dotenv
Создадим файл .env с теми переменными окружения, которые нужны нашему приложению. Помните, что .env-файл не нужно хранить в системе контроля версий, добавьте его в .gitignore.
import os
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), ‘.env’)
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
Такой файл .env можно применять для всех переменных конфигурации, но для переменных окружения FLASK_APP и FLASK_DEBUG использовать его нельзя. Дело в том, что без этих переменных не обойтись уже в начале загрузки приложения.
Итак, теперь вы понимаете, с какой целью используются и как применяются переменные окружения Python.