16
$\begingroup$

I am having some difficulty understanding the correct syntax to enable a line by line processing of a file using a WolframScript. What I would like to do to mimic this simple python pipe in Mathematica. Take a python file myfunction.py:

#!/usr/bin/env python
import sys
def myfunction():
    for line in sys.stdin:
        data = line.strip().split("\t")
        print "{d[0]}\t{d[1]}".format(d=data)

myfunction()

What this script is doing is taking a text file with tab delimited columns, split at the tabs and then output the first two entries with a tab between them.

Imagine a text file texfile.txt

col11\tcol12\tcol13\tcol14
col21\tcol22\tcol23\tcol24
col31\tcol32\tcol33\tcol34

In a terminal run

$> cat testfile.txt | ./myfunction.py

which prints the output for each line in the file. So I would like to create a WolframScript file that does the same as myfunction.py and can be used in the same way. I've tried various combinations within the script such as:

#!/usr/local/bin/WolframScript -linewise -print -script

tmp = StringSplit[ReadLine[$ScriptCommandLine], "\t"];
tmp[[1]] <> "\t" <> tmp[[2]]

and

#!/usr/local/bin/WolframScript -linewise -print -script

tmp = StringSplit[ReadLine[$ScriptInputString], "\t"];
tmp[[1]] <> "\t" <> tmp[[2]]

and

#!/usr/local/bin/WolframScript -linewise -print -script

tmp = StringSplit[ReadLine[#], "\t"]&;
tmp[[1]] <> "\t" <> tmp[[2]]

and then

$> cat testfile.txt | ./mywolframscript.m

All of the above fail with errors. I can't help feeling this should be trivial but need a pointer to help with the syntax.

Additional reference

Edit

Having got working syntax I have found another issue. I had assumed that -linewise would enable line by line reading. When I use this on a large file what seems to occur is that WolframScript attempts to read the entire file into memory and then, presumably, process it line by line. As a result the small python code runs well on text files of several hundred MB whereas the wolfram script causing a freeze with CPU usage hitting 100%.

So exactly how does someone write a Wolfram script to read a text file in line by line (analogous to ReadLine in a notebook) and achieve what can be achieved in python with trivial code?

Edit Dec 17, 2016

Wolfram Tech Support advise that it is not possible to create a Wolfram script that does the same as the python script above.

The current design decision was based on the fact that the WLS can be run through the cloud. Because the cloud evaluations are all done in one shot, all the data needs to be read in before it evaluates. Local running of WLS needs a special case to handle reading continuous input, but that has not been developed yet.

Personally I would think that the ability to read files into memory on the cloud is not infinite. There would be many cases in data science where files may be multiple GB. Of course files can be split and other work around possible by why would you do that when it is trivial in python? More to the point how can Mathematica in 2016 not be able to do things that are trivial in python?

$\endgroup$
5
  • $\begingroup$ wolframscript -linewise -code 'tmp=StringSplit[$ScriptInputString,"\t"];tmp[[1]] <> "\t" <> tmp[[2]]' < testfile.txt does work. So it is not a problem with your syntax. $\endgroup$
    – grbl
    Nov 25, 2016 at 11:10
  • $\begingroup$ The documentation of $ScriptInputString says "If the Wolfram Language kernel is run in a way other than via a wolframscript mechanism, the $ScriptInputString gives None." Maybe the problem is that you are calling WolframScript with a shebang from a script-file? $\endgroup$
    – grbl
    Nov 25, 2016 at 11:12
  • $\begingroup$ If you remove the shebang from you script and call it with wolframscript -linewise -file mywolframscript.wl < testfile.txt it works, also. $\endgroup$
    – grbl
    Nov 25, 2016 at 11:16
  • $\begingroup$ @grbl I am wanting to run a Unix script. I know how to run your suggestion but that is not the answer to my question $\endgroup$ Nov 25, 2016 at 21:13
  • $\begingroup$ I was wrong about the shebang line, it is explicitly supported. $\endgroup$
    – Szabolcs
    Nov 27, 2016 at 11:07

2 Answers 2

5
$\begingroup$

Here is another solution which more closely resembles the functionality of the original python script. It works with both Mathematica 10 and 11 and reads from standard input one line at a time.

#!/usr/local/bin/WolframScript -script

myFunction[] := Module[{stdin, line, data},
    stdin = OpenRead["!cat"];
    While[ StringQ[ line = ReadLine[stdin] ],
        data = StringSplit[line, "\t"];
        Print@ToString@StringForm["`1`\t`2`", Sequence@@data];
    ]
]

myFunction[]

Note that the function uses the trick OpenRead["!cat"] to read lines from standard input, because the Wolfram language does not support a built-in stdin stream.

$\endgroup$
3
  • 1
    $\begingroup$ This will also handle standard input from terminal. $\endgroup$
    – Szabolcs
    Nov 27, 2016 at 10:02
  • $\begingroup$ the thing that appealed about -linewise in the shebang was that it was supposed to read line by line and stop at end of file, i.e. without the need to formally test each input line in your code. Also when does the stream get closed in this above code? FWIW in addition to While one of the many variations I tried was using FixedPointList and NestWhileList printing at each iteration/input line, which stops when EndOfFile is reached. But this is not good for large files. $\endgroup$ Nov 27, 2016 at 10:43
  • 2
    $\begingroup$ @MikeHoneychurch But then it turns out that it doesn't stop at the end of file marker. It stops when input doesn't come immediately. They probably committed this mistake: stackoverflow.com/questions/5431941/… $\endgroup$
    – Szabolcs
    Nov 27, 2016 at 11:09
5
$\begingroup$

This works for me:

#!/Applications/Mathematica11.app/Contents/MacOS/wolframscript -linewise -file

Print@StringRiffle[
    Take[StringSplit[$ScriptInputString, "\t"], 2],
    "\t"
]

Then

./script.m < file.txt

But there's a problem when the input to wolframscript is not immediate.

cat file.txt | wolframscript -linewise -file script.m

works. But

cat | wolframscript -linewise -file script.m

and typing the input on the terminal doesn't work. This seems to be a timing issue. Generally, if the input is not immediate then wolfrmscript will just quit. For example,

echo foo | wolframscript -linewise -code '$ScriptInputString'

works because echo is fast but

wolframscript -code 'foo' | wolframscript -linewise -code '$ScriptInputString'

does not work because wolframscript itself is slow.

Edit (by Mike H)

I'm taking the liberty of adding the solution that worked for me to this answer. The two problems with my attempts were:

1) using -script instead of -file. I had assumed -file was not for the shebang but for direct entry to the command line to be followed by the filename.

2) Using ReadLine with $ScriptInputString

So the version of mywolframscript.m that worked (?) was

#!/usr/local/bin/WolframScript -linewise -print -file

tmp = StringSplit[$ScriptInputString, "\t"];
tmp[[1]] <> "\t" <> tmp[[2]]

so that

$> cat testfile.txt | ./mywolframscript.m

gave the same result as the python code that I was attempting to reproduce. Although on reflection it doesn't appear as though output was produced line by line.

$\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.