alex chen alex chen - 5 months ago 84
Python Question

How can I use PHP call python script return result in realtime?

I used PHP to call python script successfully and got the result . But I have to wait for the end of script running without anything output. It looks not friendly to my customer.

How can I return the script results to the PHP web in realtime ?

For instance ,for code below , I want to the PHP web will show output message in realtime instead of show them together at the end . How can I change my code?
Thank you .

PHP Code:

<?php
$k = $_REQUEST['k'];
if (!empty($k))
{
$k = trim($k);
$a = array();
exec('python ./some.py '.$k, $a);
echo $a[0];
}
?>


Python Code:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys

def do_some(a):
print 'test1'
time.sleep(30)
print 'test2'

if __name__ == '__main__':
print 'Now the python scritp running'
time.sleep(20)
a = sys.argv[1]
if a:
print 'Now print something'
T = do_some(a)

Answer

By specification, exec stop the calling program until the end of the callee. After that, you get back the output in a variable.

If you want to send data as soon as they are produced, you should use popen. It will fork a new process, but will not block the caller. So you can perform other tasks, like looping to read the sub-process output line by line to send it to your client. Something like that:

$handle = popen("python ./some.py ", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer<br/>\n";
    ob_flush();
}
pclose($handle)
Comments