Today I tried using Mathematica's plotting capabilities to display the output of a C++ program. This made me wonder whether it is possible to somehow tell a Mathematica script to read from STDIN and then do something with that, a la
#/usr/local/bin/MathematicaScript -script
(* Mathematica plotting script *)
data = ReadStream["STDIN"];
plot = ListPlot[data];
Export[plot, ...];
which can then be used like
./cppDataGenerator | mathematicaPlotScript
However, I couldn't find much on that in the documentation, the entries always focus on output or string streams, and trial and error didn't yield a result either.
So the question is: How can I make a Mathematica script listen on the standard input?
Answer
Extending on nixeagle's answer, here's what I've come up with.
First of all, the thing I overlooked is the 3rd/5th bullet point when clicking More Information in the help for Input
/InputString
, it could not be hidden any better:
When no front end is used, Input reads from standard input.
Well that answers that, the rest was finding out how these two functions work. To my knowledge, their difference is that InputString
reads STDIN like any other language, while Input
interprets STDIN as Mathematica input directly; therefore, I assume that, for practical purposes, Input[] == ToExpression[InputString[]]
.
So let's try that out:
#!/usr/local/bin/MathematicaScript -script
Print@Input[];
> echo "2^10" | ./mscript
1024
Now back to my plotting problem, there is still an issue: Input
seems to stop reading when it encounters a new line, which is of course not desired when giving a large file to the script; I'd much rather have it stop at the EOF byte. However, I wasn't able to find a setting that changes this behavior.
Comments
Post a Comment