如何运行外部命令并在 Perl 中捕获其输出? [英] How can I run an external command and capture its output in Perl?

查看:26
本文介绍了如何运行外部命令并在 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:

  1. 运行prg,只得到它的stdout.
  2. 运行prg,只得到它的stderr.
  3. 运行prg,分别得到它的stdoutstderr.
  1. Run prg, get its stdout only.
  2. Run prg, get its stderr only.
  3. Run prg, get its stdout and stderr, separately.

推荐答案

您可以使用 backtics 来执行您的外部程序并捕获其 stdoutstderr.

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`;

要同时捕获 stdoutstderr,您可以执行以下操作:

To capture both stdout and stderr you can do:

$output = `cmd 2>&1`;

使用上述内容,您将无法区分 stderrstdout.将 stdoutstderr 分开可以重定向到一个单独的文件并读取文件:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆