shell.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import logging
  2. import subprocess
  3. import threading
  4. from core.NeuronModule import NeuronModule, MissingParameterException
  5. logging.basicConfig()
  6. logger = logging.getLogger("kalliope")
  7. class AsyncShell(threading.Thread):
  8. def __init__(self, cmd):
  9. self.stdout = None
  10. self.stderr = None
  11. self.cmd = cmd
  12. threading.Thread.__init__(self)
  13. def run(self):
  14. p = subprocess.Popen(self.cmd,
  15. shell=True,
  16. stdout=subprocess.PIPE,
  17. stderr=subprocess.PIPE)
  18. self.stdout, self.stderr = p.communicate()
  19. class Shell(NeuronModule):
  20. def __init__(self, **kwargs):
  21. super(Shell, self).__init__(**kwargs)
  22. # get the command
  23. self.cmd = kwargs.get('cmd', None)
  24. # get if the user select a blocking command or not
  25. self.async = kwargs.get('async', False)
  26. # check parameters
  27. if self._is_parameters_ok():
  28. # run the command
  29. if not self.async:
  30. p = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  31. (output, err) = p.communicate()
  32. message = {
  33. "output": output,
  34. "returncode": p.returncode
  35. }
  36. self.say(message)
  37. else:
  38. async_shell = AsyncShell(cmd=self.cmd)
  39. async_shell.start()
  40. def _is_parameters_ok(self):
  41. """
  42. Check if received parameters are ok to perform operations in the neuron
  43. :return: true if parameters are ok, raise an exception otherwise
  44. """
  45. if self.cmd is None:
  46. raise MissingParameterException("cmd parameter required")
  47. return True