7

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 ?

xslittlegrass
  • 27,549
  • 9
  • 97
  • 186

1 Answers1

10

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."
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • 1
    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.) –  Sep 12 '14 at 07:40
  • @Rahul I am not at all surprised but I didn't know the syntax. Would you consider adding a Mac example to my answer? – Mr.Wizard Sep 12 '14 at 07:53
  • 2
    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. –  Sep 12 '14 at 08:23
  • 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"}]. – István Zachar Sep 30 '15 at 08:03
  • @István Sorry, I have not tried to do that and I don't wish to spend the time on it at the moment. Perhaps next month I will feel more motivated. – Mr.Wizard Oct 08 '15 at 05:23
  • 1
    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" ]. – István Zachar Oct 08 '15 at 08:28