samuelschaefer samuelschaefer - 1 year ago 74
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)

The documentation states that the all output of the program is written to the
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:

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', $output);
Traceback (most recent call last):
File "", line 2, in <module>
x = 1/0

array only contains
starting python
, and
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

I did try shell_exec and passthru, but without success.

Answer Source

Redirect stderr to stdout

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