shell.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. cmd = kwargs.get('cmd', None)
  24. # get if the user select a blocking command or not
  25. async = kwargs.get('async', False)
  26. if cmd is None:
  27. raise MissingParameterException("cmd parameter required")
  28. # run the command
  29. if not async:
  30. p = subprocess.Popen(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=cmd)
  39. async_shell.start()