如何在 Symfony2 应用程序的控制器中执行命令并在 Twig 模板中实时打印输出

2024-01-03

我需要在 Symfony2 应用程序的控制器中执行持久命令,并将终端的输出实时返回给用户。

我读过这个:

http://symfony.com/doc/current/components/process.html#getting-real-time-process-output http://symfony.com/doc/current/components/process.html#getting-real-time-process-output

我不知道如何在 Twig 模板中实时打印终端输出。

EDIT:感谢Matteo的代码和用户评论,最终的实现是:

/**
 * @Route("/genera-xxx-r", name="commission_generate_r_xxx")
 * @Method({"GET"})
 */
public function generateRXXXsAction()
{
    //remove time constraints if your script last very long
    set_time_limit(0);        

    $rFolderPath = $this->container->getParameter('xxx_settings')['r_setting_folder_path'];
    $script = 'R --slave -f ' . $rFolderPath . 'main.R';

    $response = new StreamedResponse();
    $process = new Process($script);
    $response->setCallback(function() use ($process) {
        $process->run(function ($type, $buffer) {
            //if you don't want to render a template, please refer to the @Matteo's reply
            echo $this->renderView('AppBundle:Commission:_process.html.twig',
                array(
                    'type' => $type,
                    'buffer' => $buffer
                ));
            //according to @Ilmari Karonen a flush call could fix some buffering issues
            flush();
        });
    });
    $response->setStatusCode(200);
    return $response;
}

如果您需要启动一个简单的 shell 脚本并捕获输出,您可以使用流响应 http://symfony.com/doc/current/components/http_foundation/introduction.html#streaming-a-response连同Process您发布的回调。

作为示例,假设您有一个非常简单的 bash 脚本,如下所示:

loop.sh

for i in {1..500}
do
   echo "Welcome $i times"
done

您可以像这样实施您的操作:

/**
 * @Route("/process", name="_processaction")
 */
public function processAction()
{
    // If your script take a very long time:
    // set_time_limit(0);
    $script='/path-script/.../loop.sh';
    $process = new Process($script);

    $response->setCallback(function() use ($process) {
        $process->run(function ($type, $buffer) {
            if (Process::ERR === $type) {
                echo 'ERR > '.$buffer;
            } else {
                echo 'OUT > '.$buffer;
                echo '<br>';
            }
        });
    });
    $response->setStatusCode(200);
    return $response;
}

并且取决于缓冲区长度,您可以得到如下输出:

.....
OUT > Welcome 40 times Welcome 41 times 
OUT > Welcome 42 times Welcome 43 times 
OUT > Welcome 44 times Welcome 45 times 
OUT > Welcome 46 times Welcome 47 times 
OUT > Welcome 48 times 
OUT > Welcome 49 times Welcome 50 times 
OUT > Welcome 51 times Welcome 52 times 
OUT > Welcome 53 times 
.....

您可以使用渲染控制器将其包装在页面的一部分中,例如:

<div id="process">
    {{ render(controller(
        'AcmeDemoBundle:Test:processAction'
    )) }}
</div>

更多信息here http://symfony.com/doc/current/book/templating.html#embedding-controllers

希望这有帮助

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Symfony2 应用程序的控制器中执行命令并在 Twig 模板中实时打印输出 的相关文章

随机推荐