You can call an external (shell) command cmd
without showing a command window by using the pipe syntax "!"<>cmd
. This can be used in place of a filename with any Mathematica function that opens a file for reading. For example:
Import["!dir", "Text"]
Read["!dir"]
(opens stream, must be closed)
OpenRead["!dir"]
, followed by Read
, ReadList
etc to grab the command output (opens stream, must be closed).
ReadList["!dir"]
BinaryReadList["!dir"]
Find["!dir", "tmp.txt"]
will return the first lines of cmd output containing "tmp.txt"
These functions can be found in guide/LowLevelFileOperations in the Documentation Center.
The general rules used for resolving file names are documented in the Files and Streams tutorial. This is something that has had improvements for Version 9, e.g. URLs can now appear where filenames can go and the resource will be opened by making an HTTP request.
However, be alert that OpenRead["!cmd"]
and Read["!cmd"]
leave an open InputStream
object, that in some cases (depending on the cmd
) must be closed before a new, similar command can be run. Closing what has been opened by Read["!dir"]
is not trivial, as Read
does not return the InputStream
object it opens, so one has to check Streams[]
. In some cases (again, depending on cmd
), an InputStream["!cmd"]
object might not be closable (Mathematica hangs) as the running process must be killed via taskkill
, the Task Manager or similar. Furthermore, commands that start permanent processes (unlike dir
that is terminated immediately) can cause Mathematica to wait until the process is closed outside of Mathematica, e.g.:
ReadList["!notepad.exe"]
Print["next"]
the Print
statement is not evaluated and Mathematica does not continue until the appearing Notepad window is closed. On the other hand
stream = OpenRead["!notepad.exe"]
Print["next"]
the Print
is evaluated right after the first line and we get back the cursor. The stream
of course could only be closed if the Notepad window is closed, so the next example causes Mathematica to wait, and only the first Print
is printed before closing Notepad:
stream = OpenRead["!notepad.exe"]
Print["next"]
Close@stream
Print["more"]