Advertisement
Guest User

Windows Async process tracking

a guest
Jan 14th, 2016
849
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. from time import sleep, time
  2. import asyncio.subprocess
  3. import sys
  4. t0 = time()
  5.  
  6. @asyncio.coroutine
  7. def start_process():
  8.     script = """
  9. from time import sleep
  10.  
  11. print('Lets count to 5')
  12. for i in range(1, 6):
  13.    sleep(1)
  14.    print(i)
  15.  
  16. print('Good bye!')
  17.    """
  18.  
  19.     # Create the subprocess, redirect the standard output into a pipe
  20.     create = asyncio.create_subprocess_exec(sys.executable, '-c', script,
  21.                                             stdout=asyncio.subprocess.PIPE,
  22.                                             bufsize=0)
  23.     proc = yield from create
  24.     return proc
  25.  
  26. @asyncio.coroutine
  27. def readline(proc):
  28.  
  29.     # Read one line of output
  30.     data = yield from proc.stdout.readline()
  31.     line = data.decode('ascii').rstrip()
  32.  
  33.     return line
  34.  
  35. @asyncio.coroutine
  36. def follow_process():
  37.     print('Starting Process')
  38.     proc = yield from start_process()
  39.     print('Following Process...')
  40.     while proc.returncode is None:
  41.         line = yield from readline(proc)
  42.         sleep(0.01)
  43.         if line:
  44.             print(line)
  45.         else:
  46.             print('.', end='')
  47.    
  48.     print()
  49.     print('Return Code', proc.returncode)
  50.    
  51.  
  52. if sys.platform == "win32":
  53.     loop = asyncio.ProactorEventLoop()
  54.     asyncio.set_event_loop(loop)
  55. else:
  56.     loop = asyncio.get_event_loop()
  57.  
  58. loop.run_until_complete(follow_process())
  59. print('done')
  60. loop.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement