alex chen alex chen - 1 year ago 197
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:

$k = $_REQUEST['k'];
if (!empty($k))
$k = trim($k);
$a = array();
exec('python ./ '.$k, $a);
echo $a[0];

Python Code:

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

def do_some(a):
print 'test1'
print 'test2'

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

Answer Source

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 ./ ", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer<br/>\n";