6
$\begingroup$

Or maybe a better question is - how can I get a stdin stream? I need to run on Linux.

I did look at Reading from STDIN, or: how to pipe data into Mathematica, but that talks about text data. I need to import an image, sent to standard output by another program.

According to Mathematica documentation, there is no pre-defined standard input stream, there's only $Output, which is standard output, and $Input, which is the script being executed. There are only 2 functions that read from standard input in the expected way - Input, which tries to read a Mathematica expression, and InputString, which tries to read a string till it gets a newline. Neither of these is good for reading non-text data.

What I would prefer to do is read from a stream, preferably using Import. I want to use this Mathematica script in a shell script, and pipe data to it.

I tried Import[OpenRead["/dev/stdin"]], but this only seems to work if I have an actual file on disk and I redirect input using <. It doesn't work if I pipe data to the Mathematica script.

$\endgroup$
2
  • $\begingroup$ tough one.. you can call InputString in a loop but I dont think you can discern whether each string was terminated by a newline, eof, etc.. $\endgroup$
    – george2079
    May 30, 2013 at 18:21
  • $\begingroup$ Exactly. :( Mathematica's so powerful, it's a pity that this one thing is so difficult. $\endgroup$
    – Ashley
    May 30, 2013 at 18:34

1 Answer 1

4
$\begingroup$

It turns out if you run an exteral process it gets stdin..

img=Import["!python readstdin.py","tiff"];
Print[Dimensions[ImageData[img]]];

where my python script is just this:

import sys
print sys.stdin.read()

seems to work:

math -script script.m < file.tiff
(* {900,1200,3} *)

Edit .. even better..:

img=Import["!cat -","tiff"];
$\endgroup$
4
  • 2
    $\begingroup$ Actually if you call cat without any argument, it also copies stdin to stdout. So you can just omit the - and write img=Import["!cat","tiff"]. $\endgroup$
    – celtschk
    May 30, 2013 at 20:12
  • $\begingroup$ Wow, the only solution is to run another process? :) I guess I'll accept it if there's no other way. $\endgroup$
    – Ashley
    May 30, 2013 at 20:47
  • $\begingroup$ @george2079 How would you do this on windows without python installed? $\endgroup$
    – William
    Jun 26, 2013 at 18:32
  • 1
    $\begingroup$ You could install CoreUtils for Windows, which has cat, or maybe use type, if it can direct everything from its std input to its std output. $\endgroup$
    – Ashley
    Jul 8, 2013 at 21:06

Your Answer

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

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