如何在同一行显示 Laravel artisan 命令输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25388430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display Laravel artisan command output on same line?
提问by eComEvo
I would like to display processing progress using a simple series of dots. This is easy in the browser, just do echo '.'
and it goes on the same line, but how do I do this on the same line when sending data to the artisan commandline?
我想使用一系列简单的点来显示处理进度。这在浏览器中很容易,只需执行echo '.'
并在同一行上进行,但是在将数据发送到工匠命令行时如何在同一行上执行此操作?
Each subsequent call to $this->info('.')
puts the dot on a new line.
每次后续调用都会$this->info('.')
将点放在新行上。
回答by marcanuy
The method infouses writeln, it adds a newline at the end, you need to use writeinstead.
方法info使用writeln,它在末尾添加一个换行符,您需要使用write代替。
//in your command
$this->output->write('my inline message', false);
$this->output->write('my inline message continues', false);
回答by Jonas Carlbaum
Probably a little bit of topic, since you want a series of dots only. But you can easily present a progress bar in artisan commands using built in functionality in Laravel.
可能有点主题,因为您只想要一系列点。但是您可以使用 Laravel 中的内置功能轻松地在工匠命令中显示进度条。
Declare a class variable like this:
像这样声明一个类变量:
protected $progressbar;
And initialize the progress bar like this, lets say in fire() method:
并像这样初始化进度条,让我们在 fire() 方法中说:
$this->progressbar = $this->getHelperSet()->get('progress');
$this->progressbar->start($this->output, Model::count());
And then do something like this:
然后做这样的事情:
foreach (Model::all() as $instance)
{
$this->progressbar->advance(); //do stuff before or after this
}
And finilize the progress when done by calling this:
并在完成后通过调用以下方法完成进度:
$this->progressbar->finish();
Update: For Laravel 5.1+The simpler syntax is even more convenient:
更新:对于 Laravel 5.1+更简单的语法更方便:
- Initialize
$bar = $this->output->createProgressBar(count($foo));
- Advance
$bar->advance();
- Finish
$bar->finish();
- 初始化
$bar = $this->output->createProgressBar(count($foo));
- 进步
$bar->advance();
- 结束
$bar->finish();
回答by Igor Pantovi?
If you look at the source, you will see that $this->info
is actually just a shortcut for $this->output->writeln
: Source.
如果您查看源代码,您会发现它$this->info
实际上只是$this->output->writeln
: Source的快捷方式。
You could use $this->output->write('<info>.</info>')
to make it inline.
你可以$this->output->write('<info>.</info>')
用来使它内联。
If you find yourself using this often you can make your own helper method like:
如果您发现自己经常使用它,则可以制作自己的辅助方法,例如:
public function inlineInfo($string)
{
$this->output->write("<info>$string</info>");
}