shell.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. """
  9. Class used to run an asynchrone Shell command
  10. .. notes:: Impossible to get the success code of the command
  11. """
  12. def __init__(self, cmd):
  13. self.stdout = None
  14. self.stderr = None
  15. self.cmd = cmd
  16. threading.Thread.__init__(self)
  17. def run(self):
  18. p = subprocess.Popen(self.cmd,
  19. shell=True,
  20. stdout=subprocess.PIPE,
  21. stderr=subprocess.PIPE)
  22. self.stdout, self.stderr = p.communicate()
  23. class Shell(NeuronModule):
  24. """
  25. Run a shell command in a synchron mode
  26. """
  27. def __init__(self, **kwargs):
  28. super(Shell, self).__init__(**kwargs)
  29. # get the command
  30. self.cmd = kwargs.get('cmd', None)
  31. # get if the user select a blocking command or not
  32. self.async = kwargs.get('async', False)
  33. # check parameters
  34. if self._is_parameters_ok():
  35. # run the command
  36. if not self.async:
  37. p = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  38. (output, err) = p.communicate()
  39. self.output = output
  40. self.returncode = p.returncode
  41. message = {
  42. "output": self.output,
  43. "returncode": self.returncode
  44. }
  45. self.say(message)
  46. else:
  47. async_shell = AsyncShell(cmd=self.cmd)
  48. async_shell.start()
  49. def _is_parameters_ok(self):
  50. """
  51. Check if received parameters are ok to perform operations in the neuron
  52. :return: true if parameters are ok, raise an exception otherwise
  53. .. raises:: MissingParameterException
  54. """
  55. if self.cmd is None:
  56. raise MissingParameterException("cmd parameter required")
  57. return True