Search code examples
pythonsubprocesspopen

Python popen() to exit while loop when see python prompt


I'm running a python program (my_file.py) which at the end of process becomes python prompt. I thus can't get out of the while loop. p.stdout.readline() waits for something to happen.

Any suggestion how to break the while loop. p.pole() will also probably remain null as there is some background automation associated with my_file.py.

I need the break condition to be ">>>" prompt with no activity.

import subprocess
from subprocess import Popen, PIPE
import sys, time
for iteration in range(25):
    p=Popen(r"python my_file.py",
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            shell=False,
            encoding='utf-8',
            errors='replace',
            universal_newlines=True)
    while True:
        realtime_output = p.stdout.readline()
        if realtime_output == '': #and p.poll() is not None:
            break
        else:
            print(realtime_output.strip(), flush=True)
    print("--------------- PythonSV session for {} iteration is complete -----------\n\n".format(iteration + 1))
    #subprocess.Popen("taskkill /F /T /PID %i" % p.pid, shell=True)
    Popen.terminate(p)
    time.sleep(1)

Solution

  • Tried following option where read() trying to find '\n>>>' is the break condition and it worked.

    import subprocess
    from subprocess import Popen, PIPE
    import sys, time
    for iteration in range(30):
        p=Popen(["python", r"my_file.py"],
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                shell=False,
                encoding='utf-8',
                errors='replace',
                universal_newlines=True)
        output = ''
        while not output.endswith('\n>>>'):
            c=p.stdout.read(1)
            output+=c
            sys.stdout.write(c)
        Popen.terminate(p)
        time.sleep(1)