Suppose I have a simple C++ program that takes in inputs and outputs some string. Like this (actual program is much more complicated but still text based):
$ ./game
$ what kind of game? type r for regular, s for special.
$ r
$ choose a number from 1 - 10
$ 1
$ no try again
$ 2
$ no try again
$ 5
$ yes you WIN!
I haven't used Python before, but is it possible to write a python script to run this program, feeds it input, and outputs the results to standard output? I have ask the question here about running it using C++ but it seems much too complicated. It would be awesome it you could direct me to some code examples. Any help would be appreciated.
Use pexpect .
Normal stdin/stdout piping usually doesn't work, because the standard library facilities in the parent and child processes tend to buffer I/O more aggressively when a file descriptor isn't a TTY (via the isatty
call). Obviously, you can fix this in the parent, since you own that code; just call flush at appropriate points. But often the child process is running some preexisting code that you don't own. The pexpect module feeds the child process a pseudo-tty, which tricks the child into thinking it's talking to a console. This is the same trick that GUI terminals like xterm and rxvt use.
You might be interested in Cram , which is a Python tool for testing command line options.
If you're up to it you can use my testing framework which includes a Python version of expect
. The original expect
program allows you to "converse" with interactive programs just like that. But this framework includes a Python expect.py module that you can use instead.
See http://code.google.com/p/pycopia/
The module is in the process subpackage.
You could also use pexpect, but I wrote my own because I didn't like that one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.