用ruby在命令提示符中重写以前的输出行

时间:2021-11-23 00:14:00

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.

我已经运行了输出一行的命令行程序,然后稍后更新这一行。但是使用ruby,我只能输出一行,然后是另一行。

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.

显示下载的filesize和传输速度的ruby脚本输出行每次都会被覆盖,而不是将更新的值作为一个完整的新行列出。

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?

我目前正在使用put来生成输出,这显然不是为本例设计的。有不同的输出方法可以达到这个结果吗?

1 个解决方案

#1


38  

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:

使用\r将光标移到行的开头。你不应该使用put,因为它添加了\n,而应该使用print。是这样的:

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).

但有一件事要记住:\r不会删除任何内容,它只会将光标移回来,所以您需要用空格填充输出,以便覆盖以前的输出(如果时间更长的话)。

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.

默认情况下,当将\n打印到标准输出时,刷新缓冲区。现在您可能需要使用STDOUT。打印后刷新以确保文本立即被打印出来。

#1


38  

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:

使用\r将光标移到行的开头。你不应该使用put,因为它添加了\n,而应该使用print。是这样的:

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).

但有一件事要记住:\r不会删除任何内容,它只会将光标移回来,所以您需要用空格填充输出,以便覆盖以前的输出(如果时间更长的话)。

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.

默认情况下,当将\n打印到标准输出时,刷新缓冲区。现在您可能需要使用STDOUT。打印后刷新以确保文本立即被打印出来。