Making a system call that returns the stdout outpu

2019-01-05 02:39发布

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".)

27条回答
beautiful°
2楼-- · 2019-01-05 02:56

Icon/Unicon:

stream := open("ls", "p")
while line := read(stream) do { 
    # stuff
}

The docs call this a pipe. One of the good things is that it makes the output look like you're just reading a file. It also means you can write to the app's stdin, if you must.

查看更多
爷的心禁止访问
3楼-- · 2019-01-05 02:59

Erlang:

os:cmd("ls")
查看更多
看我几分像从前
4楼-- · 2019-01-05 03:00

Yet another way to do it in Perl (TIMTOWTDI)

$output = <<`END`;
ls
END

This is specially useful when embedding a relatively large shell script in a Perl program

查看更多
Explosion°爆炸
5楼-- · 2019-01-05 03:02

An alternative method in perl

$output = qx/ls/;

This had the advantage that you can choose your delimiters, making it possible to use ` in the command (though IMHO you should reconsider your design if you really need to do that). Another important advantage is that if you use single quotes as delimiter, variables will not be interpolated (a very useful)

查看更多
beautiful°
6楼-- · 2019-01-05 03:03

In shell

OUTPUT=`ls`

or alternatively

OUTPUT=$(ls)

This second method is better because it allows nesting, but isn't supported by all shells, unlike the first method.

查看更多
家丑人穷心不美
7楼-- · 2019-01-05 03:04

Perl:

$output = `foo`;

ADDED: This is really a multi-way tie. The above is also valid PHP, and Ruby, for example, uses the same backtick notation as well.

查看更多
登录 后发表回答