我需要在我的 Symfony2 应用程序的控制器中执行一个持久的命令,并将终端的输出实时返回给用户。
我读过这个:
http://symfony.com/doc/current/components/process.html#getting-real-time-process-output
我不知道如何在 Twig 模板中实时打印终端输出。
编辑: 感谢 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;
}