php:捕获命令输出 [英] php : Capturing the command output

查看:81
本文介绍了php:捕获命令输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using exec function to execute the specific executable files in 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.

谢谢.

推荐答案

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

The second argument $output only captures STDOUT from your executable. Error messages are usually sent to STDERR so 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.

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

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

我已经在 www.php.net/exec <上进行了阅读/a>,这似乎可行.

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

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

编辑2

似乎Windows也使用这种Bourne风格的输出重定向语法,因此示例也适用于Windows.

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

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

这篇关于php:捕获命令输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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