5

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.

1

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You might be interested in Cram, which is a Python tool for testing command line options.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.