I like to do use this in my scripts:
cat("Saving...")
do_something_slow()
cat("\rSaved\n")
Run Code Online (Sandbox Code Playgroud)
The problem is that the carriage return is applied without erasing the rest of the line, so I get this:
Savedg...
Run Code Online (Sandbox Code Playgroud)
To fix it I can do:
cat("\rSaved\033[K\n")
Run Code Online (Sandbox Code Playgroud)
但它有点丑。有没有更简单的方法?
假设您希望所有消息连续出现在一行上,那么来点异想天开的怎么样?
cleancat <- function(astring, width=80) {
# Reserves a line of 80 (default) characters
# and uses it for serial updates
require("stringr")
astring <- paste("\r", astring, sep="")
cat(str_pad(astring, 80, "right"))
# pretend to do something slow
# delete this line if cleancat is used in production
Sys.sleep(0.5)
}
# imitate printing a series of updates
test <- lapply(c("Saving -",
"Saving \\",
"Saving |",
"Saving /",
"Saving -",
"Saving \\",
"Saving |",
"Saving /",
"Saved"), cleancat)
Run Code Online (Sandbox Code Playgroud)
当然,您需要加载stringr包并在您的环境中设置cleancat功能,您可能认为这更丑陋......
我喜欢使用message()而不是cat()用于生成消息。例如:
cat("Saving..."); cat("\rSaved\n")
返回:
Savdg...
Run Code Online (Sandbox Code Playgroud)
尽管:
message("Saving..."); message("\rSaved\n")
返回:
Saving...
Saved
Run Code Online (Sandbox Code Playgroud)
编辑:
受@gauden 回答的启发,另一个功能可能是:
replaceMessage <- function(x, width = 80)
{
message("\r", rep(" ", times = width - length(x)), "\r", appendLF = F)
message(x, appendLF = F)
}
Run Code Online (Sandbox Code Playgroud)
进而:
replaceMessage("Saving..."); Sys.sleep(1); replaceMessage("Saved\n")
Run Code Online (Sandbox Code Playgroud)
笔记:
虽然replaceMessage()在 Windows 上的 Linux 和 Rterm 中的行为符合预期,但在我的 Rgui(2.15.0,Windows x64)中却表现得很奇怪。具体来说,Saving...从不显示,Saved显示后,光标width向右移动空格(本例中为80个空格)。我不知道为什么。
| 归档时间: |
|
| 查看次数: |
253 次 |
| 最近记录: |