Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Advanced version of python scripts for Home Assistant without limits

NotificationsYou must be signed in to change notification settings

AlexxIT/PythonScriptsPro

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

40 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

hacs_badge

Custom component for easy run Python Scripts from Home Assistant. Better version of defaultpython_script component.

Installation

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.

Configuration

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

Use python_script.exec service

  • The component creates thepython_script.exec service.
  • You can run an external python script located in any folder (usefile param).
  • Or you can paste python source code directly into your YAML (usesource param).
  • You canimport and use any library in your python scripts. The standardpython_script component does not allow this.
  • You can pass any variables to your script, just like in the standardpython_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 thecache: false param.

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 API
  • data - The data passed to the Python Script service call
  • logger - A logger to allow you to log messages

Run script from python file

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

Run script from inline source

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'] }"          })

Example remote SSH-command run

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 using hass API

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'})

Use python_script sensors

The component allows you to create sensors.

Config:

  • You can use inlinesource or load python code fromfile (relative path from config folder).
  • You can setname,icon,unit_of_measurement andscan_interval for your sensor.

The following variables are available in the script:

  • self.hass - TheHome Assistant API
  • self.state - Change it for update sensor value
  • self.attributes - Change it for update sensor attributes
  • logger - 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

Stars

Watchers

Forks

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp