Update command line output

前端 未结 5 1944
逝去的感伤
逝去的感伤 2021-02-05 21:33

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/

相关标签:
5条回答
  • 2021-02-05 22:05

    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
    
    0 讨论(0)
  • 2021-02-05 22:10

    You can also use the ANSI escape codes to directly control the cursor. Or you can use Term::ReadKey to do the same thing.

    0 讨论(0)
  • 2021-02-05 22:14

    I know it's not quite what you asked for, but possibly better. I happened on this same problem and so rather than deal with it too much went to using Term::ProgressBar which looks nice too.

    0 讨论(0)
  • 2021-02-05 22:19

    I had to tackle something similar to this today. If you don't mind reprinting the entire line, you could do something like this:

    print "\n";
    while (...) {
         print "\rProgress: $counter / $total";
         # do processing work here
         $counter++;
    }
    print "\n";
    

    The "\r" character is a carriage return-- it brings the cursor back to the beginning of the line. That way, anything you print out overwrites the previous progress notification's text.

    0 讨论(0)
  • 2021-02-05 22:22

    Say

    $| = 1
    

    somewhere early in your program to turn autoflushing on for the output buffer.

    Also consider using "\r" to move the cursor back to the beginning of the line, rather than trying to explicitly count how many spaces you need to move back.

    Like you said, don't print out a newline while your progress counter is running or else you will print out your progress on a separate line instead of overwriting the old line.

    0 讨论(0)
提交回复
热议问题