Guest User

Untitled

a guest
Jul 16th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. import sys
  2. import time
  3.  
  4. from io import StringIO
  5.  
  6. import subprocess
  7. from multiprocessing import Process, Pipe
  8. from threading import Thread
  9.  
  10.  
  11. # "framework" code
  12.  
  13. class TeeOut(StringIO):
  14. def __init__(self, pipe, std=sys.__stdout__):
  15. self.pipe = pipe
  16.  
  17. def write(self, s):
  18. self.pipe.send(s.strip())
  19.  
  20.  
  21. def run_capturing_process(pipe, target, args):
  22. sys.stdout = TeeOut(pipe, std=sys.__stdout__)
  23. sys.stderr = TeeOut(pipe, std=sys.__stderr__)
  24.  
  25. target(*args)
  26.  
  27. sys.stdout = sys.__stdout__
  28. sys.stderr = sys.__stderr__
  29.  
  30.  
  31. def print_stdout(pipe):
  32. while True:
  33. try:
  34. recv = pipe.recv().strip()
  35. if recv:
  36. print(recv)
  37. except EOFError:
  38. print('>> process done >>')
  39. break
  40.  
  41.  
  42. def capturing_run(target, args):
  43. parent_pipe, child_pipe = Pipe()
  44. process = Process(target=run_capturing_process, args=(child_pipe, target, args))
  45. process.start()
  46.  
  47. stdthread = Thread(target=print_stdout, args=(parent_pipe, ))
  48. stdthread.start()
  49.  
  50. process.join()
  51.  
  52. parent_pipe.close()
  53. child_pipe.close()
  54.  
  55.  
  56. # user defined code
  57.  
  58. def run_process(message):
  59. for i in range(message['range']):
  60. print(i)
  61. command = 'echo "from shell: %d"' % i
  62. exit_code = subprocess.call(command, shell=True)
  63. time.sleep(message['sleep'])
  64.  
  65.  
  66. def run(message):
  67. capturing_run(target=run_process, args=(message, ))
  68.  
  69.  
  70. if __name__ == '__main__':
  71. message = {'range': 10, 'sleep': .1}
  72. run(message)
Add Comment
Please, Sign In to add comment