php:捕获命令输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3099617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:41:18  来源:igfitidea点击:

php : Capturing the command output

php

提问by Pavunkumar

I am using exec function to execute the specific executable files in php .

我正在使用 exec 函数来执行 php 中的特定可执行文件。

exec ( $file , $output , $return_value  ) ;

When the given file executed successfully I am able to get the output in the second argument by checking the return values , So, It is working fine. But My requirement is when the command execution getting failed due to some reason. I need to get that error message of that executed program . What I need to do to get the error . through second argument we can get the successful output only . Not error message.

当给定的文件成功执行时,我可以通过检查返回值来获取第二个参数中的输出,因此,它工作正常。但我的要求是当命令执行由于某种原因失败时。我需要得到那个已执行程序的错误信息。我需要做什么才能得到错误。通过第二个参数我们只能得到成功的输出。不是错误信息。

Thanks.

谢谢。

回答by Ivar Bonsaksen

The second argument $outputonly captures STDOUTfrom your executable. Error messages are usually sent to STDERRso that they easily can be written to an error log or similar, but this means that you won't see them when you call exec.

第二个参数$output仅从STDOUT您的可执行文件中捕获。错误消息通常被发送到,STDERR以便可以轻松地将它们写入错误日志或类似内容,但这意味着您在调用exec.

If this is a linux system, you could append 2>&1to your command, in order to redirect STDERRto STDOUT. I haven't tried this, but it should forward the error messages to your $output variable.

如果这是一个 linux 系统,您可以附加2>&1到您的命令,以便重定向STDERRSTDOUT. 我还没有尝试过,但它应该将错误消息转发到您的 $output 变量。

Edit:

编辑:

I've read up on it on www.php.net/exec, and it seems this would work.

我已经在www.php.net/exec上阅读了它,似乎这可行。

exec($file.' 2>&1', $outputAndErrors, $return_value);

It is also possible to redirect the errors to a temporary file and read them separately.

也可以将错误重定向到临时文件并单独读取它们。

exec($file.' 2> '.$tmpFile, $outputOnly, $return_value);

Edit 2

编辑 2

It seems windows also uses this Bourne style output redirecting syntax, so the examples should work for windows too.

似乎 windows 也使用这种 Bourne 风格的输出重定向语法,所以这些示例也应该适用于 windows。

More on input and output streams

有关输入和输出流的更多信息

回答by EJ Campbell

If you need to keep stderr and stdout separate, try proc_open: http://php.net/manual/en/function.proc-open.php

如果您需要将 stderr 和 stdout 分开,请尝试proc_openhttp: //php.net/manual/en/function.proc-open.php

回答by Serty Oan

The $return_valuewill have the error code returned by the program which should be meaningfull enough, I don't think you can have better.

$return_value会由这应该是足够meaningfull程序返回的错误代码,我不认为你可以有更好的。