shell.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. message = {
  40. "output": output,
  41. "returncode": p.returncode
  42. }
  43. self.say(message)
  44. else:
  45. async_shell = AsyncShell(cmd=self.cmd)
  46. async_shell.start()
  47. def _is_parameters_ok(self):
  48. """
  49. Check if received parameters are ok to perform operations in the neuron
  50. :return: true if parameters are ok, raise an exception otherwise
  51. .. raises:: MissingParameterException
  52. """
  53. if self.cmd is None:
  54. raise MissingParameterException("cmd parameter required")
  55. return True