Guest User

Untitled

a guest
May 25th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. #python3.6
  2.  
  3. from subprocess import Popen, PIPE
  4. from queue import Queue, Empty
  5. from threading import Thread
  6.  
  7. class customPopen(Popen):
  8. # TODO dostep do stderr
  9. def __init__(self, *args, **kwargs):
  10. kwargs.setdefault('stdin', PIPE)
  11. kwargs.setdefault('stdout', PIPE)
  12. #kwargs.setdefault('stderr', PIPE)
  13. super(customPopen, self).__init__(*args, **kwargs)
  14.  
  15. def reader(stream):
  16. while self.returncode is None:
  17. line = stream.readline().decode()
  18. if line.strip():
  19. self.stdout_lines_queue.put(line)
  20.  
  21. self.stdout_lines_queue = Queue()
  22. self.stdout_reader_thread = Thread(target=reader, args=(self.stdout,))
  23. self.stdout_reader_thread.start()
  24.  
  25. def custom_writeline(self, x: str):
  26. if not x[-1] in ['\n', '\r\n']:
  27. x += '\n'
  28. self.stdin.write(x.encode())
  29. self.stdin.flush()
  30.  
  31. def custom_readline(self, timeout=1):
  32. try:
  33. return self.stdout_lines_queue.get(timeout=timeout)
  34. except Empty:
  35. raise TimeoutError
  36.  
  37. def terminate(self):
  38. self.stdin.close()
  39. super(customPopen, self).terminate()
  40.  
  41. def kill(self):
  42. self.stdin.close()
  43. super(customPopen, self).kill()
  44.  
  45. def wait(self, timeout=None):
  46. super(customPopen, self).wait(timeout=timeout)
  47. self.stdout_reader_thread.join(timeout=timeout)
Add Comment
Please, Sign In to add comment