Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 893
tsribioguy Avatar asked Jan 15 '23 12:01

tsribioguy


2 Answers

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()
like image 189
Adrien Plisson Avatar answered Jan 26 '23 21:01

Adrien Plisson


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.

like image 45
abarnert Avatar answered Jan 26 '23 21:01

abarnert