1

I would like to run an interactive program using python's subprocess. This interactive program starts and runs for sometime. I would like to read the stdout and process it. After running for sometime, it waits with the prompt for user input. This prompt for instance can be "tool_name> ". I wanted to detect this situation and source another script. Here is some basic code, I could come up with. Would be great, if someone can comment further on if this is the correct way to do it.

import subprocess
p = subprocess.Popen(['cli_program' 'a.txt'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
while True:
    line = p.stdout.readline()
    if not line: #this is true only when application exits
        break
    elif 'tool_name> ' in line: #wanted to detect the wait state
        p.stdin.write('source b.txt\n')
        p.stdin.flush()
    else:
        print line

Here, "cli_program" is my interactive program which will start executing the script a.txt and waits with the prompt "tool_name> ".

boppu
  • 135
  • 2
  • 3
  • 9
  • Possible duplicate of [subprocess readline hangs waiting for EOF](http://stackoverflow.com/questions/7897202/subprocess-readline-hangs-waiting-for-eof) – Ryan Haining Nov 30 '16 at 19:24
  • Perhaps [pexpect](https://pexpect.readthedocs.io/) is useful in this case. – brm Nov 30 '16 at 19:43
  • Please fix your indentation – Ryan Haining Nov 30 '16 at 22:45
  • @brm: I looked at the documentation and pexpect has a default time out of 30s and it can be increased. My program runs for very long time (>1 hr) before my expected pattern matches. Does it also works in this case? I mean how to wait for longer timeout periods which are not known upfront? – boppu Nov 30 '16 at 23:02
  • @brm. I think I figured it out; timeout should be equal to None; then pexpect will wait indefinitely. I – boppu Dec 01 '16 at 10:54

0 Answers0