os.popen2 :URGENT

John Hunter jdhunter at ace.bsd.uchicago.edu
Tue May 27 14:52:38 EDT 2003


>>>>> "Ali" == Ali Dada <afd00 at aub.edu.lb> writes:


    Ali> i need to call a command line program from python, but the
    Ali> program prompts for a user input ('y' for yes or 'n' for
    Ali> no). how can i write, using python, one of those values???

    Ali> i thought of using something like
    Ali> os.popen('my_program')[1].write('y')

Take a look at the documentation for popen

popen(command[, mode[, bufsize]])
     Open a pipe to or from COMMAND.  The return value is an open file
     object connected to the pipe, which can be read or written
     depending on whether MODE is `'r'' (default) or `'w''.  The
     BUFSIZE argument has the same meaning as the corresponding
     argument to the built-in `open()' function.  The exit status of
     the command (encoded in the format specified for `wait()') is
     available as the return value of the `close()' method of the file
     object, except that when the exit status is zero (termination
     without errors), `None' is returned.  Availability: UNIX, Windows.

The first key point for you is that popen returns a file object.  By
doing

  os.popen('my_program')[1]

you are treating the return value as a sequence type and extracting
the 2nd element of the list.  I suspect that you have been
experimenting with popen2 or popen2, each of which returns a list of
file objects.  In both of those cases the second element of the list
is stdout.

The other key point is that you should pass popen the 'w' flag if you
want to write to the process.  So you should have used:

  os.popen('my_program', 'w').write('y\n')


Here is a complete example of a program that sends input to another program.

    import os
    ph = os.popen('./get_input.py', 'w')
    ph.write('Hi\n')

And here is the program get_input.py:

    #!/usr/bin/env python
    x = raw_input('What> ')
    print 'You said', x

And the results of running the program from the shell:

    video:~/python/test> python control_get_input.py
    What> You said Hi


If you do want to have more control over the stdin and stdout of the
program you are controlling, use popen2, popen3.  Here is the example
above using popen2

    import os
    sin, sout = os.popen2('./get_input.py')
    sin.write('Hi\n')
    sin.flush()
    print sout.read(),

Good luck on your presentation!

John Hunter





More information about the Python-list mailing list