{"id":15637108,"url":"https://github.com/alexxit/pythonscriptspro","last_synced_at":"2025-04-05T08:05:44.359Z","repository":{"id":47410703,"uuid":"280849082","full_name":"AlexxIT/PythonScriptsPro","owner":"AlexxIT","description":"Advanced version of python scripts for Home Assistant without limits","archived":false,"fork":false,"pushed_at":"2024-12-07T13:08:00.000Z","size":26,"stargazers_count":130,"open_issues_count":7,"forks_count":18,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-03-29T07:05:11.421Z","etag":null,"topics":["home-assistant"],"latest_commit_sha":null,"homepage":"https://github.com/AlexxIT/Blog","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AlexxIT.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-07-19T11:13:44.000Z","updated_at":"2025-03-27T22:48:16.000Z","dependencies_parsed_at":"2024-03-17T07:42:55.583Z","dependency_job_id":"5cbd9f80-1d60-49bf-94b1-faf1ff135d20","html_url":"https://github.com/AlexxIT/PythonScriptsPro","commit_stats":{"total_commits":34,"total_committers":4,"mean_commits":8.5,"dds":0.2647058823529411,"last_synced_commit":"44e8b51b83b49df3bc36fc85725e9f70d05f20fb"},"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlexxIT%2FPythonScriptsPro","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlexxIT%2FPythonScriptsPro/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlexxIT%2FPythonScriptsPro/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AlexxIT%2FPythonScriptsPro/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AlexxIT","download_url":"https://codeload.github.com/AlexxIT/PythonScriptsPro/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247305933,"owners_count":20917208,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["home-assistant"],"created_at":"2024-10-03T11:10:11.607Z","updated_at":"2025-04-05T08:05:44.342Z","avatar_url":"https://github.com/AlexxIT.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Python Scripts for Home Assistant\n\n[![hacs_badge](https://img.shields.io/badge/HACS-Custom-orange.svg)](https://github.com/custom-components/hacs)\n\nCustom component for easy run Python Scripts from Home Assistant. Better version of default [python_script](https://www.home-assistant.io/integrations/python_script/) component.\n\n## Installation\n\n[HACS](https://hacs.xyz/) \u003e Integrations \u003e 3 dots \u003e Custom repositories \u003e URL: `AlexxIT/PythonScriptsPro`, Category: Integration \u003e Add \u003e wait \u003e PythonScriptsPro \u003e Install\n\nOr manually copy `python_script` folder from [latest release](https://github.com/AlexxIT/PythonScriptsPro/releases/latest) to `custom_components` folder.\n\n## Configuration\n\n**Important:** The component replaces the standard [python_script](https://www.home-assistant.io/integrations/python_script/) component!\n\nAdd to `configuration.yaml`:\n\n```yaml\npython_script:  # no S at the end!\n```\n\nIf you need to use additional python libraries, the component can install them:\n\n```yaml\npython_script:\n  requirements:\n  - paramiko\u003e=2.7.1\n```\n\n## Use python_script.exec service\n\n- The component creates the `python_script.exec` service.\n- You can run an external python script located in any folder (use `file` param).\n- Or you can paste python source code directly into your YAML (use `source` param).\n- You can **import** and use any library in your python scripts. The standard `python_script` component does not allow this.\n- You can pass any variables to your script, just like in the standard `python_script`.\n- 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: false` param.\n\nStarting from Home Assistant [2023.7](https://www.home-assistant.io/blog/2023/07/05/release-20237/) the service will return all your script local vars with simple types as respond.\n\nThe following variables are available in the script:\n- `hass` - The [Home Assistant API](https://www.home-assistant.io/developers/development_hass_object/)\n- `data` - The data passed to the Python Script service call\n- `logger` - A logger to allow you to log messages\n\n### Run script from python file\n\nShow Home Assistant start time in Notification. Using my another component [StartTime](https://github.com/AlexxIT/StartTime). Pass variable to script.\n\n```yaml\nscript:\n  test_file:\n    sequence:\n    - service: python_script.exec\n      data_template:  # use `data_template` if you have Jinja2 templates in params\n        file: path_to/test_file.py  # relative path from config folder\n        cache: false  # disable cache if you want change python file without reload HA\n        title: Python from file test\n        time_val: \"{{ states('sensor.start_time')|round }}\"\n```\n\n**test_file.py**\n\n```python\nlogger.debug(data)\nhass.services.call('persistent_notification', 'create', {\n  'title': data['title'],\n  'message': f\"Home Assistant starts in { data['time_val'] } seconds\"\n})\nout1 = 123  # some var for service respond\n```\n\n### Run script from inline source\n\nShow your IP address in Notification. Using `requests` library. It is installed by default with Home Assistant.\n\n```yaml\nscript:\n  test_source:\n    sequence:\n    - service: python_script.exec\n      data:\n        title: Python inline test\n        source: |\n          import requests\n          r = requests.get('https://api.ipify.org?format=json')\n          resp = r.json()\n          logger.debug(resp)\n          hass.services.call('persistent_notification', 'create', {\n            'title': data['title'],\n            'message': f\"My IP: { resp['ip'] }\"\n          })\n```\n\n### Example remote SSH-command run\n\nThis example completely repeats the logic of my other component - [SSHCommand](https://github.com/AlexxIT/SSHCommand).\n\nThere is no `paramiko` library by default, but the component can install it. This will work with Hass.io or Docker.\n\n```yaml\npython_script:\n  requirements:\n  - paramiko\u003e=2.7.1\n\nscript:\n  ssh_command:\n    sequence:\n    - service: python_script.exec\n      data:\n        file: path_to/ssh_command.py\n        host: 192.168.1.123  # optional\n        user: myusername  # optional\n        pass: mypassword  # optional\n        command: ls -la\n```\n\n**ssh_command.py**\n\n```python\nfrom paramiko import SSHClient, AutoAddPolicy\n\nhost = data.get('host', '172.17.0.1')\nport = data.get('port', 22)\nusername = data.get('user', 'pi')\npassword = data.get('pass', 'raspberry')\ncommand = data.get('command')\n\nclient = SSHClient()\nclient.set_missing_host_key_policy(AutoAddPolicy())\nclient.connect(host, port, username, password)\nstdin, stdout, stderr = client.exec_command(command)\nresp = stdout.read()\nstderr.read()\nclient.close()\n\nlogger.info(f\"SSH response:\\n{ resp.decode() }\")\n```\n\n### Example using hass API\n\nExample read states and attributes, call services and fire events in python scripts.\n\n```python\nstate1 = hass.states.get('sensor.start_time').state\nname1 = hass.states.get('sensor.start_time').attributes['friendly_name']\n\nif float(state1) \u003c 30:\n    hass.services.call('persistent_notification', 'create', {\n        'title': \"My Python Script\",\n        'message': \"Home Assistant started very quickly\"\n    })\n\n    hass.states.set('sensor.start_time', state1, {\n        'friendly_name': f\"Fast {name1}\"\n    })\n\nelse:\n    hass.services.call('persistent_notification', 'create', {\n        'title': \"My Python Script\",\n        'message': \"Home Assistant was running for a very long time\"\n    })\n\n    hass.states.set('sensor.start_time', state1, {\n        'friendly_name': f\"Slow {name1}\"\n    })\n\nhass.bus.fire('my_event_name', {\n    'param1': 'value1'\n})\n```\n\n## Use python_script sensors\n\nThe component allows you to create sensors.\n\nConfig:\n- You can use inline `source` or load python code from `file` (relative path from config folder).\n- You can set `name`, `icon`, `unit_of_measurement` and `scan_interval` for your sensor.\n\nThe following variables are available in the script:\n- `self.hass` - The [Home Assistant API](https://www.home-assistant.io/developers/development_hass_object/)\n- `self.state` - Change it for update sensor value\n- `self.attributes` - Change it for update sensor attributes\n- `logger` - A logger to allow you to log messages\n\nPython source code are compiled and cached on load. You need to restart Home Assistant if there were changes in the python source file.\n\n```yaml\nsensor:\n- platform: python_script\n  name: My IP address\n  scan_interval: '00:05:00'  # optional, default: 30s\n  source: |\n    import requests\n    r = requests.get('https://api.ipify.org?format=json')\n    self.state = r.json()['ip']\n\n- platform: python_script\n  name: My DB size\n  icon: mdi:database\n  unit_of_measurement: MB\n  scan_interval: '01:00:00'  # optional\n  source: |\n    import os\n    logger.debug(\"Update DB size\")\n    filename = self.hass.config.path('home-assistant_v2.db')\n    self.state = round(os.stat(filename).st_size / 1_000_000, 1)\n\n- platform: python_script\n  name: Instance external url  # more info https://developers.home-assistant.io/docs/instance_url/\n  scan_interval: '01:00:00'  # optional\n  source: |\n    from homeassistant.helpers import network\n    try:\n      self.state = network.get_url(\n           self.hass,\n           allow_internal=False,\n      )\n    except network.NoURLAvailableError:\n      raise MyInvalidValueError(\"Failed to find suitable URL for my integration\")\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falexxit%2Fpythonscriptspro","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falexxit%2Fpythonscriptspro","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falexxit%2Fpythonscriptspro/lists"}