SHARE
TWEET

test_async_subprocess.py

DeaD_EyE Oct 5th, 2018 134 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import sys
  2. import shlex
  3. import asyncio
  4. import os
  5.  
  6. async def run_command_async(cmd):
  7.     proc = await asyncio.create_subprocess_shell(
  8.         cmd,
  9.         stdout=asyncio.subprocess.PIPE,
  10.         stderr=asyncio.subprocess.PIPE
  11.         )
  12.     return proc
  13.  
  14.  
  15. async def stdout(proc):
  16.     '''
  17.    Redirects stdout in binary form to named pipe stdout.
  18.    The program runs until the pipe was read.
  19.    '''
  20.     try:
  21.         fifo = os.mkfifo('stdout')
  22.     except FileExistsError:
  23.         pass
  24.     with open('stdout', 'wb') as file:
  25.         while True:
  26.             data = await proc.stdout.read()
  27.             if not data:
  28.                 break
  29.             # print(data.decode(), file=sys.stdout)
  30.             file.write(data)
  31.  
  32.  
  33. async def stderr(proc):
  34.     '''
  35.    Redirects stderr as utf8 to the named pipe stderr.
  36.    '''
  37.     try:
  38.         fifo = os.mkfifo('stderr')
  39.     except FileExistsError:
  40.         pass
  41.     with open('stderr', 'w') as file:
  42.         while True:
  43.             data = await proc.stderr.read()
  44.             if not data:
  45.                 break
  46.             #print(data.decode(), file=sys.stderr)
  47.             file.write(data.decode())
  48.  
  49.  
  50. async def main(cmd):
  51.     cmd = ' '.join(cmd)
  52.     proc = await run_command_async(cmd)
  53.     #await stdout(proc)
  54.     err = stderr(proc)
  55.     out = stdout(proc)
  56.     err_task = asyncio.create_task(err)
  57.     out_task = asyncio.create_task(out)
  58.     done, pending = await asyncio.wait({err_task, out_task})
  59.     #for task in done:
  60.     #    await task
  61.  
  62. loop = asyncio.get_event_loop()
  63. #loop.run_until_complete(main(sys.argv[1:]))
  64. asyncio.run(main(sys.argv[1:]))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top