7
$\begingroup$

I'm trying to run some external command line program in Mathematica, and I have problem getting the output.

For example,

Import["!echo hello world\nexit\n", "Text"]
(*"hello world"*)

run echo and get the output.

However this doesn't work for me

Import["!g++ -v", "Text"]

I only get an empty line.

In version 10, there is the RunProcess function which seems to work

RunProcess[$SystemShell, "StandardError", "g++ -v
 exit
 "]

(*
Configured with: --prefix=/Library/Developer/CommandLineTools/usr \
--with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.51) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix
*)

My question is, can we do the same thing in version 9, using other functions ?

$\endgroup$
10
$\begingroup$

Under most operating systems you can use the 2>&1 handle redirection operator(1),(2):

Import["!foo 2>&1", "Text"]
"'foo' is not recognized as an internal or external command,
operable program or batch file."
$\endgroup$
  • 1
    $\begingroup$ Stream redirection is a UNIX thing so it should work on Linux and Mac OS X too. (I just checked on my Mac and it does indeed.) $\endgroup$ – Rahul Sep 12 '14 at 7:40
  • $\begingroup$ @Rahul I am not at all surprised but I didn't know the syntax. Would you consider adding a Mac example to my answer? $\endgroup$ – Mr.Wizard Sep 12 '14 at 7:53
  • 2
    $\begingroup$ Oh, sorry, I should have been clearer: it's exactly the same syntax. I ran Import["!g++ -v 2>&1", "Text"] and got the G++ version information inside Mathematica. $\endgroup$ – Rahul Sep 12 '14 at 8:23
  • $\begingroup$ Do you have any idea how redirection can be used with RunProcess instead of Import, Run or similar? I would like to use the nice facilities of RunProcess (like returning an association of exitcode, stdout, stderr), but am unable to figure out how to do it as nothing seems to work, e.g. RunProcess[{"foo", "> file.out"}]. $\endgroup$ – István Zachar Sep 30 '15 at 8:03
  • 1
    $\begingroup$ Oh, no worries, there is of course no obliation to explore it : ) As a matter of fact, Tech Support just answered my question: RunProcess[ $SystemShell, All, "foo > file.out" ]. $\endgroup$ – István Zachar Oct 8 '15 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.