script.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import subprocess
  2. import os
  3. import threading
  4. from kalliope.core.NeuronModule import NeuronModule, MissingParameterException, InvalidParameterException
  5. class AsyncShell(threading.Thread):
  6. """
  7. Class used to run an asynchronous Shell command
  8. .. notes:: Impossible to get the success code of the command
  9. """
  10. def __init__(self, path):
  11. self.stdout = None
  12. self.stderr = None
  13. self.path = path
  14. threading.Thread.__init__(self)
  15. def run(self):
  16. p = subprocess.Popen(self.path,
  17. shell=False,
  18. stdout=subprocess.PIPE,
  19. stderr=subprocess.PIPE)
  20. self.stdout, self.stderr = p.communicate()
  21. class Script(NeuronModule):
  22. def __init__(self, **kwargs):
  23. super(Script, self).__init__(**kwargs)
  24. self.path = kwargs.get("path", None)
  25. # get if the user select a blocking command or not
  26. self.async = kwargs.get('async', False)
  27. # check parameters
  28. if self._is_parameters_ok():
  29. # run the command
  30. if not self.async:
  31. p = subprocess.Popen(self.path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
  32. (output, err) = p.communicate()
  33. self.output = output
  34. self.returncode = p.returncode
  35. message = {
  36. "output": self.output,
  37. "returncode": self.returncode
  38. }
  39. self.say(message)
  40. else:
  41. async_shell = AsyncShell(path=self.path)
  42. async_shell.start()
  43. def _is_parameters_ok(self):
  44. """
  45. Check if received parameters are ok to perform operations in the neuron
  46. :return: true if parameters are ok, raise an exception otherwise
  47. .. raises:: MissingParameterException, InvalidParameterException
  48. """
  49. if self.path is None:
  50. raise MissingParameterException("You must provide a script path.")
  51. if not os.path.isfile(self.path):
  52. raise InvalidParameterException("Script not found or is not a file.")
  53. if not os.access(self.path, os.X_OK):
  54. raise InvalidParameterException("Script not Executable.")
  55. return True