- Notifications
You must be signed in to change notification settings - Fork17
Advanced version of python scripts for Home Assistant without limits
AlexxIT/PythonScriptsPro
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Custom component for easy run Python Scripts from Home Assistant. Better version of defaultpython_script component.
HACS > Integrations > 3 dots > Custom repositories > URL:AlexxIT/PythonScriptsPro, Category: Integration > Add > wait > PythonScriptsPro > Install
Or manually copypython_script folder fromlatest release tocustom_components folder.
Important: The component replaces the standardpython_script component!
Add toconfiguration.yaml:
python_script:# no S at the end!
If you need to use additional python libraries, the component can install them:
python_script:requirements: -paramiko>=2.7.1
- The component creates the
python_script.execservice. - You can run an external python script located in any folder (use
fileparam). - Or you can paste python source code directly into your YAML (use
sourceparam). - You canimport and use any library in your python scripts. The standard
python_scriptcomponent does not allow this. - You can pass any variables to your script, just like in the standard
python_script. - The component compile and caches the executable code for faster next launch. If you want change python file without reload HA, you can disable cache with the
cache: falseparam.
Starting from Home Assistant2023.7 the service will return all your script local vars with simple types as respond.
The following variables are available in the script:
hass- TheHome Assistant APIdata- The data passed to the Python Script service calllogger- A logger to allow you to log messages
Show Home Assistant start time in Notification. Using my another componentStartTime. Pass variable to script.
script:test_file:sequence: -service:python_script.execdata_template:# use `data_template` if you have Jinja2 templates in paramsfile:path_to/test_file.py# relative path from config foldercache:false# disable cache if you want change python file without reload HAtitle:Python from file testtime_val:"{{ states('sensor.start_time')|round }}"
test_file.py
logger.debug(data)hass.services.call('persistent_notification','create', {'title':data['title'],'message':f"Home Assistant starts in{data['time_val']} seconds"})out1=123# some var for service respond
Show your IP address in Notification. Usingrequests library. It is installed by default with Home Assistant.
script:test_source:sequence: -service:python_script.execdata:title:Python inline testsource:| import requests r = requests.get('https://api.ipify.org?format=json') resp = r.json() logger.debug(resp) hass.services.call('persistent_notification', 'create', { 'title': data['title'], 'message': f"My IP: { resp['ip'] }" })
This example completely repeats the logic of my other component -SSHCommand.
There is noparamiko library by default, but the component can install it. This will work with Hass.io or Docker.
python_script:requirements: -paramiko>=2.7.1script:ssh_command:sequence: -service:python_script.execdata:file:path_to/ssh_command.pyhost:192.168.1.123# optionaluser:myusername# optionalpass:mypassword# optionalcommand:ls -la
ssh_command.py
fromparamikoimportSSHClient,AutoAddPolicyhost=data.get('host','172.17.0.1')port=data.get('port',22)username=data.get('user','pi')password=data.get('pass','raspberry')command=data.get('command')client=SSHClient()client.set_missing_host_key_policy(AutoAddPolicy())client.connect(host,port,username,password)stdin,stdout,stderr=client.exec_command(command)resp=stdout.read()stderr.read()client.close()logger.info(f"SSH response:\n{resp.decode()}")
Example read states and attributes, call services and fire events in python scripts.
state1=hass.states.get('sensor.start_time').statename1=hass.states.get('sensor.start_time').attributes['friendly_name']iffloat(state1)<30:hass.services.call('persistent_notification','create', {'title':"My Python Script",'message':"Home Assistant started very quickly" })hass.states.set('sensor.start_time',state1, {'friendly_name':f"Fast{name1}" })else:hass.services.call('persistent_notification','create', {'title':"My Python Script",'message':"Home Assistant was running for a very long time" })hass.states.set('sensor.start_time',state1, {'friendly_name':f"Slow{name1}" })hass.bus.fire('my_event_name', {'param1':'value1'})
The component allows you to create sensors.
Config:
- You can use inline
sourceor load python code fromfile(relative path from config folder). - You can set
name,icon,unit_of_measurementandscan_intervalfor your sensor.
The following variables are available in the script:
self.hass- TheHome Assistant APIself.state- Change it for update sensor valueself.attributes- Change it for update sensor attributeslogger- A logger to allow you to log messages
Python source code are compiled and cached on load. You need to restart Home Assistant if there were changes in the python source file.
sensor:-platform:python_scriptname:My IP addressscan_interval:'00:05:00'# optional, default: 30ssource:| import requests r = requests.get('https://api.ipify.org?format=json') self.state = r.json()['ip']-platform:python_scriptname:My DB sizeicon:mdi:databaseunit_of_measurement:MBscan_interval:'01:00:00'# optionalsource:| import os logger.debug("Update DB size") filename = self.hass.config.path('home-assistant_v2.db') self.state = round(os.stat(filename).st_size / 1_000_000, 1)-platform:python_scriptname:Instance external url# more info https://developers.home-assistant.io/docs/instance_url/scan_interval:'01:00:00'# optionalsource:| from homeassistant.helpers import network try: self.state = network.get_url( self.hass, allow_internal=False, ) except network.NoURLAvailableError: raise MyInvalidValueError("Failed to find suitable URL for my integration")
About
Advanced version of python scripts for Home Assistant without limits
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Contributors4
Uh oh!
There was an error while loading.Please reload this page.