Using popen interactively

Joe Mason joe at notcharles.ca
Fri Jun 7 01:01:54 EDT 2002


I'm trying to write a CGI script which filters the output from an
executable.  The typical interaction is to print some lines to stdout
and then wait for an input on stdin.  Repeat until program finishes.
I want to take each chunk of output, wrap it in HTML and then pass it to
the web server.

So this text:

  West of House
  You are standing in an open field west of a white house, with a
  boarded front door.
  There is a small mailbox here.

  >

would get wrapped in HTML and displayed, and then I'd throw up a from
with an input box, take the text posted from the form ("open mailbox",
"go north", whatever) and send it off to the app on stdin.  ("quit"
kills the app.)

So I'm trying to use popen2.Popen3("executable-name") to get handles to
stdin and stdout.  Works fine, except that I'm not sure how to detect
when the app has stopped printing and is waiting for input.  readline()
gets the first lines ok, but then the ">" line has no newline on the
end, so it blocks.  Apparently read() is supposed to return an empty
string when it hits EOF, but it blocks too - so apparently on an
interactive file stream like this EOF isn't set when its waiting for
input.

The algorithm I'm thinking of would be something like:

  app = popen.Popen3("application")
  infile = app.fromchild
  outfile = app.tochild

  # while the app is still running...
  while app.poll() == -1:
    while infile.poll() == -1:  # except file has no poll() method
      line = infile.readline()
      # process line and output it to web form 
    # get text from web form
    outfile.write(text + "\n")

Any suggestions?

Joe 



More information about the Python-list mailing list