Skip to content

Instantly share code, notes, and snippets.

Created August 20, 2023 18:11
Show Gist options
  • Save adlerweb/03d6da364974bf17057cdec72aec431f to your computer and use it in GitHub Desktop.
Save adlerweb/03d6da364974bf17057cdec72aec431f to your computer and use it in GitHub Desktop.
HomeAssistant: Convert command_line sensors to new (2023) format
#!/usr/bin/env python3
# pip install pyyaml pyyaml-include
import yaml
from yamlinclude import YamlIncludeConstructor
import os
import sys
base_dir = os.path.expanduser('~') + '/.homeassistant/'
file_path = base_dir + 'configuration.yaml'
def include_constructor(loader, node):
Custom YAML constructor for !include directive.
filename = os.path.join(os.path.dirname(, loader.construct_scalar(node))
with open(filename, 'r') as f:
return yaml.safe_load(f)
YamlIncludeConstructor.add_to_loader_class(loader_class=yaml.FullLoader, base_dir=base_dir)
with open(file_path, 'r') as file:
data = yaml.load(file, Loader=yaml.FullLoader)
if 'sensor' in data and isinstance(data['sensor'], list):
command_line_sensors = []
remaining_sensors = []
for sensor_data in data['sensor']:
if isinstance(sensor_data, dict) and 'platform' in sensor_data and sensor_data['platform'] == 'command_line':
data['sensor'] = remaining_sensors
print("No 'sensor' section found or it's not a dictionary.")
if not 'command_line' in data:
data['command_line'] = []
converted = 0
for command_line_sensor in command_line_sensors:
command_line_sensor.pop('platform', None)
data['command_line'].append({'sensor': command_line_sensor})
converted += 1
if converted > 0:
print("-------SUGGESTED SENSOR SECTION-------")
print(yaml.dump({'sensor': data['sensor']}, default_style='', default_flow_style=False, indent=2))
print(yaml.dump({'command_line': data['command_line']}, default_style='', default_flow_style=False, indent=2))
print("-------END OF SUGGESTIONS-------")
print(f"Done - {converted} sensors converted.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment