我的 php system() 函数输出有问题。代码如下:
system("c:\\Dev-Cpp\\bin\\g++.exe c:\\wamp\\www\\hello.cpp -O3 -o c:\\wamp\\www\\hello.exe", $output);
echo $output;
因此,如果我的 hello.cpp 编译成功,我得到 0,如果没有编译,我得到 1。
如果我从 CMD 运行相同的东西而不是只给出 1,它会给我完整的错误。
如何获取 php system() 函数的完整错误?
最佳答案
您只捕获程序的返回代码,它通常是一个整数,其中 0
表示“成功”,其他任何内容都是错误代码。
如果您想捕获程序的实际输出(即 STDOUT and/or STDERR),您需要执行以下操作之一:
- 使用输出缓冲来捕获
system()
的输出:
$command = "c:\\Dev-Cpp\\bin\\g++.exe c:\\wamp\\www\\hello.cpp -O3 -o c:\\wamp\\www\\hello.exe"; ob_start(); system($command, $returnCode); $output = ob_get_clean();
- 使用
exec()
,shell_exec()
或 backticks :
exec($command, $output, $returnCode); // ...or... $output = shell_exec($command); // ...or... $output = `$command`;
如果您想捕获 STDERR 的输出(我怀疑您这样做),您可能需要将 2>&1
添加到命令字符串的末尾。
或者,您可能想查看 proc_open()
,这更复杂,但可以让您更精细地控制子进程以及它如何执行/将数据传回给您。
关于php - 从 php system() 函数获取完整输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8352636/