0

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)
Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22
Dibyendu Dey
  • 349
  • 2
  • 16

3 Answers3

0

Option 1: instead of breaking on realtime_output == '', break when you get a Python prompt

Option 2: instead of using readline(), use non-blocking read on the pipe, though it's pretty involved to get working reliably

Masklinn
  • 34,759
  • 3
  • 38
  • 57
0

How can I simulate a key press in a Python subprocess?

https://gist.github.com/waylan/2353749

When it enters Python prompt you can exit it by inputting exit().

Something along the lines of this (if you don't care about realtime output):

from subprocess import Popen, PIPE

p = Popen(["python", "my_file.py"], stdin=PIPE, stdout=PIPE, stderr=PIPE shell=True)
output, error = p.communicate(input=b'exit()')

You need to modify this further if you want to have realtime output. The gist link should give you an idea how to read and write simultaneously.

Tin Nguyen
  • 5,250
  • 1
  • 12
  • 32
0

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)
Dibyendu Dey
  • 349
  • 2
  • 16