5
$\begingroup$

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"]
ReadList[inputstream]

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?

$\endgroup$
1
  • 1
    $\begingroup$ How is the file formatted? Have you tried piping that as a string instead using either program <<< string or echo string | program? $\endgroup$
    – C. E.
    Oct 4, 2013 at 10:17

1 Answer 1

1
$\begingroup$

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

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"]
ReadList[inputstream]

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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