Writing over previously output lines in the comman

2019-01-21 23:20发布

问题:

I've run command line programs that output a line, and then update that line a moment later. But with ruby I can only seem to output a line and then another line.

What I have being output now:

Downloading file:
11MB 294K/s
12MB 307K/s
14MB 294K/s
15MB 301K/s
16MB 300K/s
Done!

And instead, I want to see this:

Downloading file:
11MB 294K/s

Followed a moment later by this:

Downloading file:
16MB 300K/s
Done!

The line my ruby script outputs that shows the downloaded filesize and transfer speed would be overwritten each time instead of listing the updated values as a whole new line.

I'm currently using puts to generate output, which clearly isn't designed for this case. Is there a different output method that can achieve this result?

回答1:

Use \r to move the cursor to the beginning of the line. And you should not be using puts as it adds \n, use print instead. Like this:

print "11MB 294K/s"
print "\r"
print "12MB 307K/s"

One thing to keep in mind though: \r doesn't delete anything, it just moves the cursor back, so you would need to pad the output with spaces to overwrite the previous output (in case it was longer).

By default when \n is printed to the standard output the buffer is flushed. Now you might need to use STDOUT.flush after print to make sure the text get printed right away.