Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


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?

share|improve this question
How is the file formatted? Have you tried piping that as a string instead using either program <<< string or echo string | program? – C. E. Oct 4 '13 at 10:17
up vote 1 down vote accepted

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";
inputstream=OpenRead["! ./external-program.x < inputFile.txt"]

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"]

Depending on the piping constructs on Windows, a similar approach may be possible.

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.