[Tutor] running an interactive program from a script

Michael Dunn Michael.Dunn at mpi.nl
Fri Jan 9 05:33:08 EST 2004


Hi Pythoneers,

I am working with an excellent series of (non-Python) programs for doing
cladistics called PHYLIP. For historical reasons these are run
interactively, with the user selecting settings to toggle from a prompt.
The little script below simulates the user experience of this:

###
#!/usr/bin/env python
# sample.py

prompt = """Settings:
 (F)loats: %(float)s
 Is (D)uck: %(duck)s
Enter F or D to change a setting, Q to quit
> """
settings = {'float':'Yes', 'duck':'No'}
toggle = {'Yes':'Maybe','Maybe':'No','No':'Yes'}
selection = ''

while selection.upper() != 'Q':
    selection = raw_input((prompt % settings))
    if selection.upper() == 'F':
        settings['float'] = toggle[settings['float']]
    if selection.upper() == 'D':
        settings['duck'] = toggle[settings['duck']]

print 'Settings are:', settings
###

The real PHYLIP programs will also  accept a text command file with
newline-delineated keystroke entries, e.g. from the command line it's
possible to run:
  sample.py < commands.txt > output
where commands.txt could contain something like:
"""
D
D
F
""".

This is obviously a pain for scripting -- you have to know how many
keystrokes necessary to toggle a value in advance, and if the options
change between versions you are lost. In the real PHYLIP programs there
are sometimes also some other messages you have to deal with (asking for
the names of input and output files etc -- all with quite regular
formats). I've been in contact with the author of the program, and it's
apparently too difficult/too much work to implement a change to the more
familiar command line style.

So my question: Is it possible to run a program like my sample.py using
a python script as a wrapper? I'd want to parse the prompt message after
each bit of input (prob. using a regex) and to carry on toggling things
until the values match the ones I had stored in a settings file. I think
I can handle the logic for toggling values and so forth, but I can't
work out how (or if it's possible)  to get python to interactively
'drive' another program. I know it would be a horrible hack -- I should
of course learn C and then fix the original programs -- but it's never
going to happen and the hack would solve my problems nicely. I've been
experimenting with the popen2 module, but I can't make it work. Is this
the right track? Any suggestions?

Thanks, Michael



More information about the Tutor mailing list