2

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.

2 Answers 2

3

Redirect stderr to stdout

$ret_val = exec('python run_python.py 2>&1', $output);
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it with: exec ( 'python run_python.py', $output,$return_var ), you'll have the error code at $return_var and the traceback at $output, and you can see it by doing

exec ( 'python run_python.py', $output,$return_var );
if ($return_var>0) {
    var_dump($output);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.