如果我通过 PHP exec() 方法编译代码,如何捕获 Java 中的语法错误?

How to catch syntax errors in Java if I am compiling the code through the PHP exec() method?

PHP 中使用 exec() 命令的代码如下所示:

exec('javac -classpath dir test.java');

我想知道如何捕获 test.java 文件中存在的语法错误。

您需要将 stderr 重定向到 stdout

2>&1 附加到命令的末尾

exec('javac -classpath dir test.java 2>&1',$op);
var_dump($op);

这里2是stderr,1是stdout

如果您使用所有 3 个 exec 参数,您将看到输出:

来自 http://php.net/manual/en/function.exec.php

string exec ( string $command [, array &$output [, int &$return_var ]] )

exec() executes the given command.
Parameters ¶

command

    The command that will be executed.
output

    If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
return_var

    If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.