2017-10-31 09:20:35 +01:00
|
|
|
import subprocess
|
|
|
|
|
2018-07-06 02:08:38 +02:00
|
|
|
from platypush.plugins import Plugin, action
|
2017-12-13 03:37:28 +01:00
|
|
|
|
2017-10-31 09:20:35 +01:00
|
|
|
|
|
|
|
class ShellPlugin(Plugin):
|
2018-06-25 19:57:43 +02:00
|
|
|
"""
|
|
|
|
Plugin to run custom shell commands.
|
|
|
|
"""
|
|
|
|
|
2018-07-06 02:08:38 +02:00
|
|
|
@action
|
2018-10-20 17:56:36 +02:00
|
|
|
def exec(self, cmd, ignore_errors=False):
|
2018-06-25 19:57:43 +02:00
|
|
|
"""
|
|
|
|
Execute a command.
|
|
|
|
|
|
|
|
:param cmd: Command to execute
|
|
|
|
:type cmd: str
|
|
|
|
|
2018-10-20 17:56:36 +02:00
|
|
|
:param ignore_errors: If set, then any errors in the command execution will be ignored. Otherwise a RuntimeError will be thrown (default value: False)
|
2018-06-25 19:57:43 +02:00
|
|
|
:returns: A response object where the ``output`` field will contain the command output as a string, and the ``errors`` field will contain whatever was sent to stderr.
|
|
|
|
"""
|
|
|
|
|
2017-10-31 09:20:35 +01:00
|
|
|
try:
|
2018-07-06 02:08:38 +02:00
|
|
|
return subprocess.check_output(
|
2017-12-13 03:37:28 +01:00
|
|
|
cmd, stderr=subprocess.STDOUT, shell=True).decode('utf-8')
|
2017-10-31 09:20:35 +01:00
|
|
|
except subprocess.CalledProcessError as e:
|
2018-10-20 17:56:36 +02:00
|
|
|
if ignore_errors:
|
|
|
|
self.logger.warning('Command {} failed with error: {}'.format(
|
|
|
|
cmd, e.output.decode('utf-8')))
|
|
|
|
else:
|
|
|
|
raise RuntimeError(e.output.decode('utf-8'))
|
2017-10-31 09:20:35 +01:00
|
|
|
|
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|
|
|
|
|