4

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?

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
tsribioguy
  • 73
  • 1
  • 6
  • 2
    Is this a C or C++ question? – Component 10 Jan 14 '13 at 21:01
  • The way you describe this, it's hard to tell whether this is a filter program (like `grep` or `sort`) that just takes a stdin stream and writes a stdout stream, or whether it's an interactive CLI program with prompts and responses (like `python` itself). If it's the former, `subprocess.communicate` is all you need; if the latter, `pexpect` is a good option, but nobody can really help you unless you ask a more specific question than "how to implement it". – abarnert Jan 14 '13 at 21:04
  • so the program in C would be a "module" in python. I want to access the functions by sending in input from python, obtaining the output of the C program, and using it in my own python code. does that make sense? – tsribioguy Jan 14 '13 at 22:01

2 Answers2

6

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()
Adrien Plisson
  • 22,486
  • 6
  • 42
  • 73
  • 1
    If output is bounded it should be written as `output = process.communicate("hello world !")[0]` as @abarnert said. Read the warnings about the direct usage of .stdin, .stdout [in the docs](http://docs.python.org/2/library/subprocess.html). In some cases you also need `stderr=PIPE`. `latin1` character encoding is not the best choice. It accepts any input so it hides errors. – jfs Jan 14 '13 at 21:21
  • also, sometimes you may need `stderr=subprocess.STDOUT`. – Adrien Plisson Jan 14 '13 at 21:47
3

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.

abarnert
  • 354,177
  • 51
  • 601
  • 671