The standard and robust method for piping to/from external commands under Windows is to create a temporary file, save the input into it, pipe it to the command and save its output to a second file. Here is a crippled version of the built-in RunThrough
(that is the standard way for piping), that omits the output, for testing purposes, and prevents the command window to pop up (you can check the definition of RunThrough
by removing its ReadProtected
attribute).
runThrough[comm_String, s_String] := Block[{in = OpenWrite[], out = OpenWrite[]},
WriteString[in, s <> "\n"]; Close /@ {in, out};
(* If[i > 2040, Print[{i, in, out}]]; *)
Read["!" <> comm <> " < " <> First@in <> " > " <> First@out];
DeleteFile@First@# & /@ {in, out}];
In the following example I called the Windows ver
command that simply returns the OS version, so it's pretty harmless to run. The problem comes when this runThrough
is run iteratively. Always precisely and reproducibly at i=2045
on my machine, error messages start to rain.
Dynamic@i
Table[runThrough["ver", "x"], {i, 10000}]
OpenRead::noopen: -- Message text not found -- (C:\...\Mathematica 9.0.1\Documentation\English\PacletDB.m) General::stream: -- Message text not found -- ($Failed) OpenWrite::noopen: -- Message text not found -- (C:\Users\...\AppData\Local\Temp\m-49f8c51e-d090-4dc3-87b4-0a5310380f70) General::stream: $Failed is not a string, InputStream[ ], or OutputStream[ ]. ...
If the commented line is uncommented (I left it for everyone to figure out the platform-dependent time of breakdown), I can see that the out
file is not created by OpenWrite
, as the result is $Failed
. It happens to any external command, even for those that properly accept input from a pipe, not just OS natives like ver
. Furthermore, somehow the kernel gets messed up, as any attempt after the messages to access the Documentation Center (for example F1-ing a function) brings up a dialog:
The file you tried to open was not found or could not be opened.
Is it a problem of OpenWrite
or I simply try to do too many things too fast and the OS cannot keep up with Mathematica
? If so, how can I overcome such unwanted effects?
(Fresh kernel, no package was loaded, Win7 64bit, Mathematica 9.0.1)