如何在Perl中运行外部命令并捕获其输出?

gam*_*ver 18 perl stdout stderr

我是Perl的新手,想知道prg在以下场景中运行外部命令(调用它)的方法:

  1. prg,stdout只得到它.
  2. prg,stderr只得到它.
  3. 运行prg,得到了stdoutstderr,分别.

cod*_*ict 27

您可以使用背景来执行外部程序并捕获它stdoutstderr.

默认情况下,反引号会丢弃stderr并仅返回stdout外部程序的内容.所以

$output = `cmd`;
Run Code Online (Sandbox Code Playgroud)

将捕获stdout程序cmd并丢弃stderr.

要捕获,stderr您可以使用shell的文件描述符:

$output = `cmd 2>&1 1>/dev/null`;
Run Code Online (Sandbox Code Playgroud)

捕获两者stdout,stderr你可以做:

$output = `cmd 2>&1`;
Run Code Online (Sandbox Code Playgroud)

使用上面的你不能者区分stderrstdout.要离开stdout,stderr可以将两者重定向到单独的文件并读取文件:

`cmd 1>stdout.txt 2>stderr.txt`;
Run Code Online (Sandbox Code Playgroud)

  • 每次使用反引号时,一只小猫就会死亡.在shell中,使用$().在perl中,使用qx. (3认同)
  • 另一种分别读取stdout和stderr而不使用临时文件的方法是使用IPC :: Open3. (2认同)

Eug*_*ash 8

在大多数情况下,您可以使用qx//运算符(或反引号).它插入字符串并使用shell执行它们,因此您可以使用重定向.