如何运行外部命令并在Perl中捕获其输出? [英] How can I run an external command and capture its output in Perl?
问题描述
我是Perl的新手,并且想知道在以下情况下运行外部命令(称为prg
)的方法:
I'm new to Perl and want to know of a way to run an external command (call it prg
) in the following scenarios:
- 运行
prg
,仅获取其stdout
. - 运行
prg
,仅获取其stderr
. - 运行
prg
,分别获取其stdout
和stderr
.
- Run
prg
, get itsstdout
only. - Run
prg
, get itsstderr
only. - Run
prg
, get itsstdout
andstderr
, separately.
推荐答案
您可以使用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
.要从stderr
中分离stdout
,可以将它们都重定向到一个单独的文件并读取文件:
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`;
这篇关于如何运行外部命令并在Perl中捕获其输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!