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.
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With