1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How do I manage a python subprocess with an infinite loop

Discussão em 'Python' iniciado por Stack, Outubro 3, 2024 às 11:22.

  1. Stack

    Stack Membro Participativo

    I want to read input from a subprocess in python, interact with it, see the results of that interaction, and then kill the process. I have the following parent and child processes.

    child.py

    from random import randint

    x = 1
    while x < 9:
    x = randint(0, 10)
    print("weeeee got", x)


    name = input("what's your name?\n")
    print("hello", name)

    x = 0
    while True:
    x += 1
    print("bad", x)


    parent.py

    import curio
    from curio import subprocess


    async def main():
    p = subprocess.Popen(
    ["./out"],
    stdout=subprocess.PIPE,
    stdin=subprocess.PIPE,
    )

    async for line in p.stdout:
    line = line.decode("ascii")
    print(p.pid, "got:", line, end="")
    if "what" in line and "name" in line:
    out, _ = await p.communicate(input=b"yaboi\n")
    print(p.pid, "got:", out.decode("ascii"), end="")
    # stuff to properly kill the process ...
    return


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


    If I run this, the parent hangs on:

    out, _ = await p.communicate(input=b"yaboi\n")


    Removing the following section from the child fixes the issue:

    x = 1
    while x < 9:
    x = randint(0, 10)
    print("weeeee got", x)


    Why doesn't it work with the infinite loop? How do I fix this?

    Edit 1: putting flush=True in the print statement does not fix the issue.

    Continue reading...

Compartilhe esta Página