本文介绍了更新命令行输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序(碰巧在 Perl 中,尽管我认为这个问题不是特定于 Perl 的)以 Progress: x/yy 形式在程序中的某一点输出状态消息其中 xyy 是一个数字,例如:Progress: 4/38.

My program (which happens to be in Perl, though I don't think this question is Perl-specific) outputs status messages at one point in the program of the form Progress: x/yy where x and yy are a number, like: Progress: 4/38.

我想在打印新状态消息时覆盖"之前的输出,这样我就不会用状态消息填充屏幕.到目前为止,我已经尝试过这个:

I'd like to "overwrite" the previous output when a new status message is printed so I don't fill the screen with status messages. So far, I've tried this:

my $progressString = "Progress\t$counter / " . $total . "\n";
print $progressString;
#do lots of processing, update $counter
my $i = 0;
while ($i < length($progressString)) {
    print "\b";
    ++$i;
}

如果我在 $progressString 中包含换行符,则不会打印退格字符.但是,如果我省略换行符,则输出缓冲区永远不会刷新,也不会打印任何内容.

The backspace character won't print if I include a newline in $progressString. If I leave out the newline, however, the output buffer is never flushed and nothing prints.

对此有什么好的解决方案?

What's a good solution for this?

推荐答案

在 STDOUT 中使用自动刷新:

Use autoflush with STDOUT:

local $| = 1; # Or use IO::Handle; STDOUT->autoflush;

print 'Progress: ';
my $progressString;
while ...
{
  # remove prev progress
  print "\b" x length($progressString) if defined $progressString;
  # do lots of processing, update $counter
  $progressString = "$counter / $total"; # No more newline
  print $progressString; # Will print, because auto-flush is on
  # end of processing
}
print "\n"; # Don't forget the trailing newline

这篇关于更新命令行输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 23:35
查看更多