0

I want to run a python script which takes about 3-5 minutes to execute in Laravel. While its running I would like to copy the print messages in between and display it on my blade template.

I have managed to do it as follows

<div>
        <h1>Application Status</h1>
        {{ print_r(auth()->user()->liveExecuteCommand("cd ../../python-script && python3 -u main.py")) }}
</div>

Heres the liveExecuteCommand function which I got from another answer here

public function liveExecuteCommand($cmd)
{

    while (@ob_end_flush()); // end all output buffers if any

    $proc = popen("$cmd 2>&1 ; echo Exit status : $?", 'r');

    $live_output = "";
    $complete_output = "";

    echo '<code><pre>';

    while (!feof($proc)) {
        $live_output = fread($proc, 4096);
        $complete_output = $complete_output . $live_output;
        echo "$live_output";
        @flush();
    }
    echo '</pre></code>';

    pclose($proc);

    // get exit status
    preg_match('/[0-9]+$/', $complete_output, $matches);

    // return exit status and intended output
    return array(
        'exit_status' => intval($matches[0]),
        'output' => str_replace("Exit status : " . $matches[0], '', $complete_output),
    );
}

My problem is: The script starts running before the HTML and css are rendered and I get a pretty basic html page instead of my usual page. Once the script is finished running, the rest of the css loads and the page looks fine. But waiting for 3-5 minutes for the page to be functional does not seem like a good idea.

I also tried using Symfony's Process but the I was unable to get the live execution working in python. I even tried the -u unbuffer flag but it didn't work. It runs the entire script and then loads the page

Is there any better way to this? Calling functions in blade just seems off to me. I also tried calling the function in the Controller but then I'd have to wait for the program to execute to pass the output to the view.

Vivek
  • 123
  • 7
  • 1
    It looks like you need sth working with pub-sub logic. One good solution would be using socket.io with laravel. Then you can listen for the changes on the log file with php or send the messages directly from python script. – Hilmi Erdem KEREN Dec 24 '18 at 13:04
  • Thanks I'll try socket.io – Vivek Dec 24 '18 at 13:12

0 Answers0