更新时间:2023-01-04 11:49:51
您可以使用 backtics 来执行您的外部程序并捕获其 stdout
和 stderr
.
You can use the backtics to execute your external program and capture its stdout
and stderr
.
默认情况下,反引号丢弃 stderr
并只返回外部程序的 stdout
.所以
By default the backticks discard the stderr
and return only the stdout
of the external program.So
$output = `cmd`;
将捕获程序cmd的stdout
并丢弃stderr
.
Will capture the stdout
of the program cmd and discard stderr
.
要仅捕获 stderr
,您可以使用 shell 的文件描述符:
To capture only stderr
you can use the shell's file descriptors as:
$output = `cmd 2>&1 1>/dev/null`;
要同时捕获 stdout
和 stderr
,您可以执行以下操作:
To capture both stdout
and stderr
you can do:
$output = `cmd 2>&1`;
使用上述内容,您将无法区分 stderr
和 stdout
.将 stdout
与 stderr
分开可以重定向到一个单独的文件并读取文件:
Using the above you'll not be able to differenciate stderr
from stdout
. To separte stdout
from stderr
can redirect both to a separate file and read the files:
`cmd 1>stdout.txt 2>stderr.txt`;