How to get content or length of current console output?

时间:2017-04-25 14:28:56

标签: r console output cat sapply

I'm looking for the functions get_output_content or at least get_output_length below, that would tell me how many characters were printed in the console.

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

In this example obviously I could easily count the characters in the input, but If I'm using other functions I may not. Can you help me build one or both of these functions ?

EDIT to clarify:

in my real situation, I cannot work upstream and count before, like in the proposed solutions, I need to count the displayed output at a given time without monitoring what's before.

here's a reproducible example looking more like what I want to achieve

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

if I was able to count what's in the console I could easily tweak my function to get something satisfying.

NEW EDIT : FYI solution to example but not to general question:

I could solve my precise issue with this, though it doesn't solve the general question, which is measuring the current output of the console when you don't have any other info.

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

1 个答案:

答案 0 :(得分:1)

像这样(?):

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