php 更新命令行输出,即进度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5265288/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:48:45  来源:igfitidea点击:

Update Command-line Output, i.e. for Progress

phpcommand-linestdoutautoflush

提问by Adam

I'd like to be able to show a progress meter in a simple PHP script on the command line. Instead of seeing

我希望能够在命令行上的简单 PHP 脚本中显示进度表。而不是看到

Progress: 0%
Progress: 1%
etc...

I'd like just the number to change, and replace the previous number, much like git clone does for example Resolving deltas: 100% (8522/8522), done..

我只想更改数字,并替换以前的数字,就像 git clone 所做的那样Resolving deltas: 100% (8522/8522), done.

While searching for this I found the same question answered in Perl, which is perfect, but I couldn't find it in PHP. Is it possible? If not, I'll resort to C.

在搜索这个时,我发现在 Perl 中回答同样的问题,这是完美的,但我在 PHP 中找不到它。是否可以?如果没有,我会求助于C。

Thanks

谢谢

Update:If anyone's interested in the C++ version, it's here.

更新:如果有人对 C++ 版本感兴趣,请点击此处

回答by Pascal MARTIN

This can be done using ANSI Escape Sequences-- see herefor a list.

这可以使用ANSI 转义序列来完成——请参见此处的列表。

In PHP, you'll use "\033"when it's indicated ESCon that page.

在 PHP 中,您将在该页面上"\033"指示时使用ESC


In your case, you could use something like this :


在你的情况下,你可以使用这样的东西:

echo "Progress :      ";  // 5 characters of padding at the end
for ($i=0 ; $i<=100 ; $i++) {
    echo "3[5D";      // Move 5 characters backward
    echo str_pad($i, 3, ' ', STR_PAD_LEFT) . " %";    // Output is always 5 characters long
    sleep(1);           // wait for a while, so we see the animation
}


I simplified a bit, making sure I always have 5 extra characters, and always displaying the same amount of data, to always move backwards by the same number of chars...


我简化了一点,确保我总是有 5 个额外的字符,并且总是显示相同数量的数据,总是向后移动相同数量的字符......

But, of course, you should be able to do much more complicated, if needed ;-)

但是,当然,如果需要,您应该能够做更复杂的事情;-)

And there are many other interesting escape sequences : colors, for instance, can enhance your output quite a bit ;-)

还有许多其他有趣的转义序列:例如,颜色可以大大增强您的输出;-)

回答by Dom

Just for the record though an old thread: Instead of using fancy ANSI Escape sequencing to move the curser back I just move it back to the beginning of the line using "\r" instead of to the beginning of the next line "\n". Add a few spaces after your echo to overwrite anything that was there previously, like e.g. so:

只是为了记录,虽然旧线程:而不是使用花哨的 ANSI Escape 序列将光标移回我只是使用“\r”将其移回行的开头而不是下一行的开头“\n” . 在 echo 后添加几个空格以覆盖以前存在的任何内容,例如:

for ($i=0 ; $i<=100 ; $i++) {
  echo "Progress: $i %   \r";
  sleep(1);
}