Search code examples
phppythonshellreal-time

Execute shell, get and display result realtime using PHP


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?


Solution

  • 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.