Perl and PHP do this with backticks. For example,
$output = `ls`;
Returns a directory listing. A similar function, system("foo")
, returns the operating system return code for the given command foo. I'm talking about a variant that returns whatever foo prints to stdout.
How do other languages do this? Is there a canonical name for this function? (I'm going with "backtick"; though maybe I could coin "syslurp".)
In C on Posix conformant systems:
Well, since this is system dependent, there are many languages that do not have a built-in wrapper for the various system calls needed.
For example, Common Lisp itself was not designed to run on any specific system. SBCL (the Steel Banks Common Lisp implementation), though, does provide an extension for Unix-like systems, as do most other CL implementations. This is much more "mighty" than just getting the output, of course (you have control over the running process, can specify all kinds of stream directions, etc., confer to the SBCL manual, chapter 6.3), but it is easy to write a little macro for this specific purpose:
Now, you can use it like this:
Perhaps you want to slurp it all into one string. The macro is trivial (though perhaps more concise code is possible):
Now you can get a string with this call:
Here's another Lisp way:
Then, to get your string:
If you want to run a command that creates prints a great deal of info to STDOUT, you can run it like this:
The last parameter preallocates a large amount of space for the output from big-writer. I'm guessing this function could be faster than reading the output stream one line at a time.