Pass value to command line

Hey there,

I was also wanting to pass arguments/parameters to a shell command. I created a new component called ‘templated_shell_command’. It is basically a copy-paste of the normal ‘shell_command’ but instead of just running the command, it passes it through the template engine first and then runs the output of that. So, you can save the following as templated_shell_command.py in your custom_components directory:

import logging
import subprocess

import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import template
from homeassistant.exceptions import TemplateError

DOMAIN = 'templated_shell_command'

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        cv.slug: cv.string,
    }),
}, extra=vol.ALLOW_EXTRA)

SHELL_COMMAND_SCHEMA = vol.Schema({})


def setup(hass, config):
    """Setup the shell_command component."""
    conf = config.get(DOMAIN, {})

    def service_handler(call):
        """Execute a shell command service."""
        try:
            cmd = template.render(hass, conf[call.service])
            subprocess.call(cmd, shell=True,
                            stdout=subprocess.DEVNULL,
                            stderr=subprocess.DEVNULL)
        except TemplateError as ex:
            if ex.args and ex.args[0].startswith("UndefinedError: 'None' has no attribute"):
                # Common during HA startup - so just a warning
                _LOGGER.warning(ex)
                return
            _LOGGER.error(ex)
        except subprocess.SubprocessError:
            _LOGGER.exception('Error running command')

    for name in conf.keys():
        hass.services.register(DOMAIN, name, service_handler,
                               schema=SHELL_COMMAND_SCHEMA)
    return True

Then, to use it, add to your config:

templated_shell_command:
  test_cmd: 'echo "{{ states.sun.sun.attributes.elevation }}" >> /tmp/templated_shell_command_test &'

and call it just as you would a normal shell command:

  service: templated_shell_command.test_cmd

As an example of how I use it, here’s how I have a input_select to pick the pan-tilt preset for my foscam that gets acted on once I change it in the web interface:

templated_shell_command:
  camera_office_preset: 'foscam_preset {{ states.input_select.camera_office_preset.state }} &'

input_select:
  camera_office_preset:
    name: 'Office camera preset'
    options:
      - 'off'
      - 'left'
      - 'right'
    initial: 'off'

automation:
  alias: "Change office camera preset"
  trigger:
    - platform: state
      entity_id: input_select.camera_office_preset
  action:
    service: templated_shell_command.camera_office_preset
7 Likes