Advertisement
AdmiralNemo

multiprocess/subprocess pipe

Mar 11th, 2014
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. import multiprocessing
  4. import os
  5. import subprocess
  6. import sys
  7. import tempfile
  8. import threading
  9. import time
  10.  
  11. t_fd, t_fn = tempfile.mkstemp()
  12. os.write(t_fd, b'''\
  13. #!/bin/sh
  14.  
  15. for i in `seq 1 40`; do
  16.    echo $i
  17.    sleep 1
  18. done
  19. ''')
  20. os.close(t_fd)
  21.  
  22.  
  23. class OutputHandler(multiprocessing.Process):
  24.  
  25.     def __init__(self):
  26.         super(OutputHandler, self).__init__()
  27.         self._pipe_r, self._pipe_w = os.pipe()
  28.         self.stdout = self.stderr = self._pipe_w
  29.         self.start()
  30.  
  31.     def run(self):
  32.         os.close(self._pipe_w)
  33.         d = os.read(self._pipe_r, 1)
  34.         while d:
  35.             sys.stderr.write(d.decode())
  36.             d = os.read(self._pipe_r, 1)
  37.  
  38.     def close(self):
  39.         os.close(self._pipe_w)
  40.  
  41.  
  42. class Runner(multiprocessing.Process):
  43.  
  44.     def __init__(self):
  45.         super(Runner, self).__init__()
  46.  
  47.     def run(self):
  48.         self.o = OutputHandler()
  49.         p = subprocess.Popen(['/bin/sh', t_fn],
  50.                              stdin=open(os.devnull),
  51.                              stdout=self.o.stdout,
  52.                              stderr=self.o.stderr)
  53.         p.wait()
  54.         self.o.close()
  55.         print('Finished')
  56.         os.unlink(t_fn)
  57.  
  58.  
  59. def main():
  60.     Runner().start()
  61.  
  62. if __name__ == '__main__':
  63.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement