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 input from the Unix shell; on the other hand, I use Windows.

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

What is the best way to do this? I read about pexpect , but not sure how to implement it; can anyone explain a better way to do this?

+4
source share
2 answers

I recommend you use the python subprocess module.

this is a replacement for calling the os.popen() function, and it allows you to execute the program while interacting with standard input / output / error flows through pipes.

usage example:

 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() 
+6
source

If you don’t need to answer interactive questions and tips, don’t worry with pexpect , just use subprocess.communicate as suggested by Adrien Plisson.

However, if you need pexpect , the best way to get started is to look at examples on your home page, then start reading the documentation as soon as you have a handle to what exactly you need to do.

+3
source

All Articles