[Python] Python - Run process and wait for output

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    I want to run a program, wait for it's output, send inputs to it and repeat until a condition.

    All I could find was questions about waiting for a program to finish, which is NOT the case. The process will still be running, it just won't be giving any (new) outputs.

    Program output is in stdout and in a log file, either can be used.
    Using linux.

    Code so far:

    import subprocess

    flag = True
    vsim = subprocess.popen(['./run_vsim'],
    stdin=subprocess.pipe,
    shell=true,
    cwd='path/to/program')
    while flag:
    with open(log_file), 'r') as f:
    for l in f:
    if condition:
    break
    vsim.stdin.write(b'do something\n')
    vsim.stdin.flush()
    vsim.stdin.write(b'do something else\n')
    vsim.stdin.flush()


    As is, the "do something" input is being sent multiple times even before the program finished starting up. Also, the log file is read before the program finishes running the command from the last while iteraction. That causes it to buffer the inputs, so I keeps executing the commands even after the condition as been met.

    I could use time.sleep after each stdin.write but since the time needed to execute each command is variable, I would need to use times longer than necessary making the python script slower. Also, that's a dumb solution to this.

    Thanks!

    Continue reading...

Compartilhe esta Página