I would say JLink
is one of the fastest ways to do this. Just use the Runtime
to start a process executing your command and collect the exit code too:
<< JLink`
RunThroughWithExitCode[cmd_String] :=
JavaBlock[Module[{ireader, istream, runtime, process, reader},
LoadJavaClass["java.lang.Runtime"];
runtime = Runtime`getRuntime[];
process = runtime@exec[cmd];
process@waitFor[];
istream = process@getInputStream[];
ireader = JavaNew["java.io.InputStreamReader", istream];
reader = JavaNew["java.io.BufferedReader", ireader];
{reader@readLine[], process@exitValue[]}
]]
And then you get
RunThroughWithExitCode["uname -a"]
(* {Linux lenerd 3.2.0-39-generic #62-Ubuntu SMP
Thu Feb 28 00:28:53 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux,
0}
*)
The same approach can be used to catch the error stream of the process
.
When you are on a system with a bash
, you could collect everything in the system call itself. This is basically the same idea that was already suggested by @ssch
RunThroughWithExitCode2[cmd_String] :=
ToExpression@Import[
"!out=\"$(eval " <> cmd <> ")\";ret=$?;echo \"{\\\"${out}\\\",${ret}}\"", "String"]
This works too and gives a list of output and return value
RunThroughWithExitCode2["which math"]
(* {"/usr/local/Wolfram/Mathematica/9.0.1/Executables/math", 0} *)
Run["ls >> /tmp/ls.txt"]
what you want ? $\endgroup$StringJoin
to build the command andFileNameJoin
for the output ? $\endgroup$RunThrough
had a bug because it didn't handle spaces properly on Windows XP. $\endgroup$Import["!bla ; echo $?"]
and knew that last part was the exit status, but that's very far from cross platform $\endgroup$