如何在同一行显示Laravel artisan命令输出?

eCo*_*Evo 14 php laravel laravel-4

我想用一系列简单的点来显示处理进度.这在浏览器中很容易,只是这样echo '.',它在同一条线上,但是如何在向artisan命令行发送数据时在同一行上执行此操作?

每次后续调用都会$this->info('.')将点放在一个新行上.

mar*_*nuy 19

方法info使用writeln,它在最后添加换行符,你需要使用write来代替.

//in your command
$this->output->write('my inline message', false);
$this->output->write('my inline message continues', false);
Run Code Online (Sandbox Code Playgroud)

  • 在播种机中使用 `$this->command->getOutput()->write(//...` (2认同)

Jon*_*aum 18

可能是一个主题,因为你只想要一系列的点.但是,您可以使用Laravel中的内置功能轻松地在工匠命令中显示进度条.

声明一个类变量,如下所示:

protected $progressbar;
Run Code Online (Sandbox Code Playgroud)

并像这样初始化进度条,让我们说在fire()方法中:

$this->progressbar = $this->getHelperSet()->get('progress');
$this->progressbar->start($this->output, Model::count());
Run Code Online (Sandbox Code Playgroud)

然后做这样的事情:

foreach (Model::all() as $instance)
{
    $this->progressbar->advance(); //do stuff before or after this
}
Run Code Online (Sandbox Code Playgroud)

并通过调用以下内容来完成进度:

$this->progressbar->finish();
Run Code Online (Sandbox Code Playgroud)

更新:对于Laravel 5.1+更简单的语法更方便:

  1. 初始化 $bar = $this->output->createProgressBar(count($foo));
  2. 预先 $bar->advance();
  3. $bar->finish();

  • 有没有办法显示命令行输出,例如`$ this-> error()`,这不会破坏进度条? (2认同)

Igo*_*vić 8

如果你查看源代码,你会发现它$this->info实际上只是一个快捷方式$this->output->writeln:Source.

您可以使用$this->output->write('<info>.</info>')它来内联.

如果你发现自己经常使用这个,你可以制作自己的帮助方法,如:

public function inlineInfo($string)
{
    $this->output->write("<info>$string</info>");
}
Run Code Online (Sandbox Code Playgroud)