使用ruby在命令提示符中写入先前输出的行 [英] Writing over previously output lines in the command prompt with ruby

查看:161
本文介绍了使用ruby在命令提示符中写入先前输出的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行了输出一行的命令行程序,然后稍后更新该行。但是用ruby我只能输出一行,然后再输出一行。

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.

我现在输出的是:

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

而我想看到的是:

Downloading file:
11MB 294K/s

稍后片刻:

Downloading file:
16MB 300K/s
Done!

我的ruby脚本输出的行显示下载的文件大小和传输速度将被覆盖,

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.

我目前使用 puts 生成输出,不是为这种情况设计的。是否有可以实现此结果的不同输出方法?

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?

推荐答案

使用 \r 将光标移动到行的开头。并且你不应该使用 puts ,因为它添加 \\\
,使用 print 。像这样:

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"

请记住一件事: \ r 不会删除任何东西,它只是将光标向后移动,因此您需要用空格填充输出以覆盖先前的输出(如果更长)

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

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

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.

这篇关于使用ruby在命令提示符中写入先前输出的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆