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.