Controlling an external program with Python

Donn Cave donn at u.washington.edu
Mon Jun 26 12:11:47 EDT 2000


Quoth ge at nowhere.none (Grant Edwards):
| In article <kuzoobue0g.fsf at lasipalatsi.fi>, Erno Kuusela wrote:
|>>>>>> "Tony" == Tony Keating <keating at mech.uq.edu.au> writes:
|>
|>    Tony> start the program, then send various strings to the program,
|>    Tony> read some output from the program then send some more
|>    Tony> strings to the program.
|>
|> there are a couple of expect modules for python (so named because
|> there is an old tcl-based language called expect for doing just this).
|> parnassus lists 3 modules (<URL:http://www.vex.net/parnassus/
|> apyllo.py?find=expect>), i haven't
|> used any of them however...
|
| Or you can roll your own using the popen2 module.

OK, but check to see if your application will work reliably on
a pipe, before you put too much work a pipe solution.  I append
a short sample program that works with the shell as a remote
application, but deadlocks with awk.  The awk behavior is what
I would expect from most programs, so normally you're sunk.

	Donn Cave, donn at u.washington.edu
----------------------------------------
import popen2

# rfd, wfd = popen2.popen2(('/bin/sh', '-c', 'echo hi!; read ans; echo $ans'), 0)
rfd, wfd = popen2.popen2(('/bin/awk', 'BEGIN {print "hi!"} {print "bye"; exit}'), 0)
hi = rfd.readline()
# ^ Deadlock here.  To fix, move write+flush up before readline, which lets
# awk exit - and flush its output - before we need to read it.
print 'application says', repr(hi)
wfd.write('OK.\n')
wfd.flush()
hi = rfd.readline()
print 'application responds', repr(hi)



More information about the Python-list mailing list