I would like to wrap an external process with a python subprocess to add a control on the input and output. I created a small wrapper program, and managed to change the input and output send to the internal process when I need it. I couldn't return output without calling the inner process - see the TODO inside my code import asyncio import sys async def main(program: str, cmd_args): process = await asyncio.create_subprocess_exec( program, *cmd_args.split(" "), stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, ) async def read_stdout(): while output := await process.stdout.readline(): sys.stdout.write(" " + output.decode("utf-8")) sys.stdout.flush() async def read_stdin(): while l := await asyncio.to_thread(sys.stdin.readline): yield l.strip() stdout_task = asyncio.create_task(read_stdout()) async for line in read_stdin(): if some_condition(line): # TODO - return output without calling the inner process pass else: process.stdin.write(line.encode("utf-8")) process.stdin.write(b"\n") await process.stdin.drain() process.stdin.close() await stdout_task await process.wait() if __name__ == "__main__": asyncio.run(main(sys.argv[1], sys.argv[2])) Continue reading...