How to write python code to access input and output from a program written in C?

4.6k Views Asked by At

There is a program written and compiled in C, with typical data input from a Unix shell; on the other hand, I'm using Windows.

I need to send input to this program from the output of my own code written in Python.

What is the best way to go about doing this? I've read about pexpect, but not sure really how to implement it; can anyone explain the best way to go about this?

2

There are 2 best solutions below

2
On

i recommend you use the python subprocess module.

it is the replacement of the os.popen() function call, and it allows to execute a program while interacting with its standard input/output/error streams through pipes.

example use:

import subprocess

process = subprocess.Popen("test.exe", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
input,output = process.stdin,process.stdout

input.write("hello world !")
print(output.read().decode('latin1'))

input.close()
output.close()
status = process.wait()
0
On

If you don't need to deal with responding to interactive questions and prompts, don't bother with pexpect, just use subprocess.communicate, as suggested by Adrien Plisson.

However, if you do need pexpect, the best way to get started is to look through the examples on its home page, then start reading the documentation once you've got a handle on what exactly you need to do.