Read system environment variables with python-Part 1

Outline / Purpose

Use ʻos.environ` to get system environment variables. The setting information used in the application can be written in the setting file etc. and DI can be done. If there are many configuration files or the development status (develop-staging-release) is complicated Maintenance costs increase and the chances of making mistakes increase. I wondered if it would be possible to reduce the maintenance cost of the configuration file by holding the configuration information in the system environment variables. I checked a program that uses system environment variables.

Digging deeper about os.environ

ʻOs.environ` holds system environment variables as a dictionary. You can refer to the system environment variables until python is executed. os library

To get system environment variables

To get the system environment variable, specify the system environment variable name in ʻos.environ. The result is the same as the SET% system environment variable name%` executed on the command prompt.

$ python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> print(os.environ['HOMEDRIVE'])
C:
>>>

KeyError occurs if you specify a system environment variable name that does not exist.

$ python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['TEST']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python38\lib\os.py", line 673, in __getitem__
    raise KeyError(key) from None
KeyError: 'TEST'
>>>

If you don't want to raise an exception for a system environment variable name that doesn't exist, use ʻos.getenv (key, default = value) . If the key does not exist, the specified value of defaultis returned. Ifdefault is not specified, it will be None. The same applies to ʻos.environ.get (key). ʻOs.getenv (key, default = value) is an alias for ʻos.environ.get (key).

$ python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> value = os.getenv("TEST", "defaultvalue")
>>> print(f"TEST={value}")
TEST=defaultvalue
>>>

To update system environment variables

Since ʻos.environis a dictionary type, just set system environment variables and values If the system environment variable name does not exist, it will be added, and if it exists, it will be overwritten. To delete it, use the del statement.del os.environ [system environment variable name]`

$ python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> value = os.environ["TEST"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python38\lib\os.py", line 673, in __getitem__
    raise KeyError(key) from None
KeyError: 'TEST'
>>> os.environ["TEST"] = "PYTHON"
>>> value = os.environ["TEST"]
>>> print(f"TEST={value}")
TEST=PYTHON
>>> os.environ["TEST"] = "PYTHON3"
>>> value = os.environ["TEST"]
>>> print(f"TEST={value}")
TEST=PYTHON3
>>> del os.environ["TEST"]
>>> value = os.environ["TEST"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python38\lib\os.py", line 673, in __getitem__
    raise KeyError(key) from None
KeyError: 'TEST'
>>>

There is also a function that sets system environment variables without directly modifying ʻos.environ. You can add or update system environment variables with putenv (key, value), which is paired with getenv`, but the official documentation has such a note.

quoting os.putenv

If putenv () is supported, making an assignment to an item in os.environ will automatically convert it to the corresponding call to putenv (). If you call putenv () directly, os.environ will not be updated, so it is actually better to assign it to an item in os.environ. Sends the audit event os.putenv with the arguments key and value.

It seems like a bug that the system environment variables updated by putenv () are not reflected in ʻos.environ`, but you can handle it with dictionary type data.

Recommended Posts

Read system environment variables with python-Part 1
Read system environment variables with python-Part 2
Set environment variables with lambda-uploader
Shell variables, environment variables
[Python] Get environment variables
What are environment variables?
Python environment with docker-compose
[For beginners] Read DB authentication information from environment variables
Read excel with openpyxl
Virtual environment with Python 3.6
mongodb access with pymongo
[Note] Operate MongoDB with Python
Basics of touching MongoDB with MongoEngine
Manipulating strings with pandas group by
Read system environment variables with python-Part 1
Read system environment variables with python-Part 2
Environment variables when using Tkinter
Read csv with python pandas
Easy tox environment with Jenkins
Read image coordinates with Python-matplotlib
Handle Go environment variables (viper)
Create an environment with virtualenv
Minimal website environment with django
Install Python environment with Anaconda
Manage python environment with virtualenv
What are environment variables? (Linux)
venv environment with windows powershell
Handle environment variables in Python
Build python3 environment with ubuntu 16.04
ML environment construction with Miniconda
HTTP environment variables in Flask
Prepare python3 environment with Docker
Build python environment with direnv
Presentation Support System with Python3
Switch virtual environment with jupyter
Read json data with python