shell.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import logging
  2. import subprocess
  3. import threading
  4. from kalliope.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. self.query = kwargs.get('query', None)
  34. if self.query is not None:
  35. self.cmd = self.cmd + "\"" + self.query +"\""
  36. # check parameters
  37. if self._is_parameters_ok():
  38. # run the command
  39. if not self.async:
  40. p = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  41. (output, err) = p.communicate()
  42. self.output = output
  43. self.returncode = p.returncode
  44. message = {
  45. "output": self.output,
  46. "returncode": self.returncode
  47. }
  48. self.say(message)
  49. else:
  50. async_shell = AsyncShell(cmd=self.cmd)
  51. async_shell.start()
  52. def _is_parameters_ok(self):
  53. """
  54. Check if received parameters are ok to perform operations in the neuron
  55. :return: true if parameters are ok, raise an exception otherwise
  56. .. raises:: MissingParameterException
  57. """
  58. if self.cmd is None:
  59. raise MissingParameterException("cmd parameter required")
  60. return True