6

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.

Ashley
  • 269
  • 1
  • 6
  • 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.. – george2079 May 30 '13 at 18:21
  • Exactly. :( Mathematica's so powerful, it's a pity that this one thing is so difficult. – Ashley May 30 '13 at 18:34

1 Answers1

4

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"];
george2079
  • 38,913
  • 1
  • 43
  • 110
  • 2
    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"]. – celtschk May 30 '13 at 20:12
  • Wow, the only solution is to run another process? :) I guess I'll accept it if there's no other way. – Ashley May 30 '13 at 20:47
  • @george2079 How would you do this on windows without python installed? – William Jun 26 '13 at 18:32
  • 1
    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. – Ashley Jul 08 '13 at 21:06