2

I need to do some long process using Python which will be called using PHP(my main language) and display the result real time.

Lets say this is my Python script(a.py).

import time

for x in range(10):
    print "S;adasdasd;",x
    time.sleep(0.5)

I have try so many example from internet but always get same result. PHP always wait until script is done then displaying it.

Here is one of so many code i have tried.

    header( 'Content-type: text/html; charset=utf-8' );
    $handle = popen('python folder\\a.py', 'r');
    while (!feof($handle)) {
            echo fgets($handle);
            flush();
            ob_flush();
    }
    pclose($handle);

Did I miss something?

5
  • Try adding a character set as a header in your PHP. See here: stackoverflow.com/a/12740522/128161 Commented Jun 28, 2016 at 8:55
  • tried but gives same result, i have update the question Commented Jun 28, 2016 at 8:57
  • How about using fread($handle, 1024); instead of fgets? Commented Jun 28, 2016 at 9:00
  • nope.still gives me the same result, did i need to config my PHP or something? Commented Jun 28, 2016 at 9:04
  • I'm not sure to be honest. It could be something to do with popen rather than using fopen. Is it possible you could alter the code slightly to use fopen and set the URL to a website and just output the contents line by line. If that works then the issue would lie within popen rather than your server config, so may help to narrow down the issue. Commented Jun 28, 2016 at 9:08

1 Answer 1

5

PHP always wait until script is done then displaying it.

In this case, it's not PHP's fault; it's because Python fully buffers its standard output if that goes to a pipe. Fortunately, Python has the handy option -u to disable stdout and stderr buffering, so using

    $handle = popen('python -u folder\\a.py', 'r');

solves the problem. See also Disable output buffering.

Sign up to request clarification or add additional context in comments.

1 Comment

Been looking for a solution for long and this really fixed it. Can't believe it was that simple.

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.