1

I am trying to asynchronously run another python script and get its unbuffered command line output using gevent.

I already have such an example working with asyncio, but I need to use gevent for compatability reasons.

main.py

import asyncio

async def get_output():
    p = await asyncio.create_subprocess_exec('python', 'sub.py', 'watch', 'ls', '-u',
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.STDOUT,
    )
    while True:
        line = await p.stdout.readline()
        if not line:
            break
        print(line.decode("utf-8").replace("\r\n", ""))
    await p.wait()


async def print_stuff():
    for i in range(100):
        print("." + str(i))
        await asyncio.sleep(1)


async def main():
    asyncio.create_task(print_stuff())
    await asyncio.sleep(10)
    await get_output()


if __name__ == "__main__":
    asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
    asyncio.run(main())

sub.py

import time
import asyncio
import sys


async def main():
    for i in range(100):
        print(i)
        await asyncio.sleep(1)

if __name__ == "__main__":
    asyncio.run(main())

I found an answer here, but that involves running a function as a subprocess, whereas I want to run a python file.

I T
  • 53
  • 1
  • 5

0 Answers0