dpxkkhu1812 2018-12-24 11:06
浏览 73

如何在laravel刀片中显示python脚本的实时输出

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么