samuelschaefer samuelschaefer - 1 year ago 68
PHP Question

handle Python exception/errors in PHP

I am running some python script from within a PHP script using PHP's

exec($cmd, $output)
function.

The documentation states that the all output of the program is written to the
$output
array. This works fine, however, if the Python code raises an exception/error, the function seems to just return NULL, without any information on the exception.

for example:

run_python.py

print('starting python')
x = 1/0 #This will raise an error
print('complete python')


Running it from the interactive PHP shell yields the following:

php > $output = '';
php > $ret_val = exec('python run_python.py', $output);
Traceback (most recent call last):
File "run_python.py", line 2, in <module>
x = 1/0


The
$output
array only contains
starting python
, and
$ret_val
contains nothing.

This is OK for the interactive shell, but I am running the code from a web interface and the error information is never displayed. Is there any way to capture that error and then display it using
echo
?

I did try shell_exec and passthru, but without success.

Answer Source

Redirect stderr to stdout

$ret_val = exec('python run_python.py 2>&1', $output);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download