# Is it possible to interact with an external program's command-line interface?

I am performing a calculation in Mathematica which relies on calls to an external program that acts as a black box for calculating a function $f$, and I would like to know if it is possible for Mathematica to interact with a command-line interface that asks for user input.

At the moment I am writing the arguments to my function $f$ in some external file inputFile.txt, and then running the external executable using one of the Run-related syntaxes:

inputstream=OpenRead["! ./external-program.x < inputFile.txt"]


For the record, I'm running Mathematica 9 on Ubuntu 12.04.

While this is a perfectly OK way to do things, it does mean I need to write to a file, have external-program read it, and then delete the file. For a long calculation with many such calls, it is overhead that I'd like to avoid.

My external program does allow for command-line interaction, at least with a human user on a terminal, and this does not require piping in an already-written file. In practice, you run

./external-program.x


on a command line, and you are then required to input the multiple arguments and press Enter after them.

Is it possible to automate this sort of behaviour from within Mathematica?

-
How is the file formatted? Have you tried piping that as a string instead using either program <<< string or echo string | program? –  Pickett Oct 4 '13 at 10:17

As Anon pointed out, my problem was more of a poor knowledge of Unix rather than incomplete Mathematica chops, and a judicious use of pipes solves the issue.

Thus, instead of exporting a string to a file and using that as an input, as I had,

inputstring="sample input data";
Export["inputFile.txt",inputstring,"Text"]


it is possible to pipe the string in directly on the command line using | and an echo command:

inputstring="sample input data";
inputstream=OpenRead["!echo \" "<>inputstring<>" \" | ./external-program.x < inputFile.txt"]

I would still be stumped, however, with a more sophisticated application that requires actual interaction $-$ keyboard input that responds adaptively to the external program's output $-$, which is fortunately not my case. If someone does find a way and posts it here I will be happy to accept such an answer instead.