Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python to run a C++ program and test it

Tags:

c++

python

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.

like image 757
Mark Avatar asked Jul 21 '11 22:07

Mark


People also ask

Can I run C program in Python?

The python default implementation is written in C programming and it's called CPython. So it's not very uncommon to use C functions in a python program. In this tutorial, we learned how to easily call C functions in a python program.

How do I read a .C file in Python?

Reading a File Line-by-Line The first example is inspired by the two programming languages - C and C++. It is probably the most intuitive approach - open the file using the open() function, read the file line-by-line using the readline() method, and output the line immediately after reading.

Can we run C program in PyCharm?

Of course you can create a file, rename it to *. c and keep it in your project. PyCharm will be fine with opening that file for you, with C syntax highlighting.


2 Answers

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.

like image 72
Marcelo Cantos Avatar answered Sep 26 '22 15:09

Marcelo Cantos


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

like image 23
Ned Batchelder Avatar answered Sep 26 '22 15:09

Ned Batchelder