1

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)

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I am sorry that I am too busy to reply for your answer instantly.Yes,your answer is right,and I used your code solve my problem.Thank you again.

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.