R 如何获取当前控制台输出的内容或长度?
我正在寻找下面的函数get_output_content或至少get_output_length,这将告诉我控制台中打印了多少字符R 如何获取当前控制台输出的内容或长度?,r,console,output,cat,sapply,R,Console,Output,Cat,Sapply,我正在寻找下面的函数get_output_content或至少get_output_length,这将告诉我控制台中打印了多少字符 test <- function(){ cat("ab") cat("\b") cat("cd") c <- get_output_content() # "acd" (I'd be happy with "ab\bcd" as well) l <- get_output_length() # 3 return
test <- function(){
cat("ab")
cat("\b")
cat("cd")
c <- get_output_content() # "acd" (I'd be happy with "ab\bcd" as well)
l <- get_output_length() # 3
return(list(c,l))
}
test()
test类似这样的(?)
testnchar(capture.output(cat)(“ab\bcd”))
?或者sink()
在这里可能更方便。我想我可以把它沉到某个地方,计算我需要计算的数量,然后在控制台上取消墨水并重新打印,在每次迭代中都会这样做,但这会带来很大的开销!
library(pbapply)
my_files <- paste0(1000:1,".pdf")
work_on_pdf <- function(pdf_file){
Sys.sleep(0.001)
}
report <- pbsapply(my_files,work_on_pdf) # the simple version, but I want to add the pdf name next to the bar to have more info about my progress
# so I tried this but it's not satisfying because it "eats" some of the current output of pbapply
report <- pbsapply(my_files,function(x){
buffer_length <- 25
work_on_pdf(x)
catmsg <- paste0(c( # my additional message, which is in 3 parts:
rep("\b",buffer_length), # (1) eat 25 characters
x, # (2) print filename
rep(" ",buffer_length-nchar(x))), # (3) print spaces to cover up what may have been printed before
collapse="")
cat(catmsg)
})
library(pbapply)
my_files <- paste0(1000:1,".pdf")
work_on_pdf <- function(pdf_file){
Sys.sleep(0.01)
}
pbsapply2 <- function(X,FUN,FUN2){
# FUN2 will give the additional message
pbsapply(X,function(x){
msg <- FUN2(x)
cat(msg)
output <- FUN(x)
eraser <- paste0(c(
rep("\b",nchar(msg)), # go back to position before additional message
rep(" ",nchar(msg)), # cover with blank spaces
rep("\b",nchar(msg))), # go back again to initial position
collapse="")
cat(eraser)
return(output)
})
}
report <- pbsapply2(my_files,work_on_pdf,function(x) paste("filename:",x))
test <- function(){
c <- paste0(capture.output(cat("ab")),
capture.output(cat("\b")),
capture.output(cat("cd")))
n <- nchar(c)
l <- length(c)
return(list(c,n,l))
}
test()