【问题标题】:How to get content or length of current console output?如何获取当前控制台输出的内容或长度?
【发布时间】:2017-04-25 14:28:55
【问题描述】:

我正在寻找下面的函数 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(list(c,l))
}
test()

在这个例子中,显然我可以很容易地计算输入中的字符,但如果我使用其他函数,我可能不会。你能帮我建立这些功能中的一个或两个吗?

编辑澄清:

在我的实际情况下,我无法在上游工作和之前计数,就像在建议的解决方案中一样,我需要在给定时间计算显示的输出而不监控之前的输出。

这是一个可重现的示例,看起来更像我想要实现的目标

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

【问题讨论】:

  • nchar(capture.output(cat("ab\bcd"))) ?
  • sink()在这里可能更方便
  • 我想我可以将它下沉到某个地方,计算我需要计算的内容,然后在每次迭代时在控制台上取消下沉并重新打印它,这会奏效,但开销很大!

标签: r console output cat sapply


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    相关资源
    最近更新 更多