PythonScriptsPro

repository·master·Indexed 40 days ago

https://github.com/alexxit/pythonscriptspro

A custom Home Assistant component that enhances the default python_script integration. It enables running arbitrary Python code via the python_script.exec service or as sensors, with support for importing external libraries via a requirements key and passing complex data.

Tokens
1.5K
Snippets
6
Records
6
Agent score
50%

What's inside PythonScriptsPro

  1. Install PythonScriptsPro via HACS or Manual Installation

    master

    You can install PythonScriptsPro using one of two methods:

    1. HACS: Search for AlexxIT/PythonScriptsPro in Custom repositories and install the Integration.
    2. Manual: Copy the python_script folder from the latest release to your Home Assistant custom_components folder.

    Note: This component replaces the standard Home Assistant python_script component.

    # No specific command, follow HACS or manual folder copy instructions.
  2. Configure PythonScriptsPro and install Python requirements

    master

    Add the following to your configuration.yaml to enable the component. If your scripts require external libraries (e.g., paramiko), list them under the requirements key:

    python_script:
      requirements:
      - paramiko>=2.7.1
  3. Run Python scripts from inline source

    master

    You can execute Python code directly within your Home Assistant service calls using the source parameter. This is useful for short snippets or when you don't want to manage separate files.

    Example: Fetching IP via requests

    script:
      test_source:
        sequence:
        - service: python_script.exec
          data:
            title: Python inline test
            source: |
              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'] }"
              })
  4. Run Python scripts from a file

    master

    To execute a Python file located in your configuration directory, use the file parameter in the python_script.exec service. You can pass variables using data_template if you are using Jinja2 templates.

    YAML Configuration:

    script:
      test_file:
        sequence:
        - service: python_script.exec
          data_template:
            file: path_to/test_file.py
            cache: false
            title: Python from file test
            time_val: "{{ states('sensor.start_time')|round }}"

    Python File (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  # This variable is returned as a response
    script:
      test_file:
        sequence:
        - service: python_script.exec
          data_template:
            file: path_to/test_file.py
            cache: false
            title: Python from file test
            time_val: "{{ states('sensor.start_time')|round }}"
    logger.debug(data)
    hass.services.call('persistent_notification', 'create', {
      'title': data['title'],
      'message': f"Home Assistant starts in { data['time_val'] } seconds"
    })
    out1 = 123
  5. Use the python_script.exec service

    master

    The component provides the python_script.exec service, which allows you to run Python code in two ways:

    1. From a file: Use the file parameter with a path relative to your configuration folder. Use cache: false to apply changes to the file without restarting Home Assistant.
    2. From inline source: Use the source parameter to paste Python code directly into your YAML.

    Unlike the standard python_script component, you can import any library (provided they are in your requirements).

    Available Variables in Scripts

    When running via the service, the following variables are injected into your script:

    • hass: The Home Assistant API object.
    • data: A dictionary containing the parameters passed to the service call.
    • logger: A logger instance for message logging.

    Starting from Home Assistant 2023.7, the service returns local script variables (with simple types) as a response.

    # Example: Running a file
    service: python_script.exec
    data:
      file: path_to/script.py
      cache: false
      param1: value1
    
    # Example: Running inline source
    service: python_script.exec
    data:
      source: |
        import requests
        r = requests.get('https://api.ipify.org?format=json')
        logger.info(r.json())
  6. Create Python-based sensors

    master

    The component allows you to define custom sensors using the python_script platform. You can provide code via source (inline) or file (relative path from config folder).

    Sensor Configuration Options

    • name: The name of the sensor.
    • icon: The icon to use.
    • unit_of_measurement: The unit for the sensor value.
    • scan_interval: How often to run the script (default: 30s).
    • device_class: The device class (e.g., connectivity).

    Available Variables in Sensor Scripts

    When running as a sensor, the following variables are available:

    • self.hass: The Home Assistant API object.
    • self.state: Set this to update the sensor's state.
    • self.attributes: A dictionary to update the sensor's attributes.
    • logger: A logger instance.

    Note: Sensor scripts are compiled and cached on load. You must restart Home Assistant to apply changes made to the Python source files.

    Example: IP Address Sensor

    sensor:
    - platform: python_script
      name: My IP address
      scan_interval: '00:05:00'
      source: |
        import requests
        r = requests.get('https://api.ipify.org?format=json')
        self.state = r.json()['ip']