1
我正在尋找函數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(貓( 「AB \ BCD」)))'? – Frank
或'sink()'在這裏可能更方便 –
我想我可以將它沉到某個地方,計算我需要計算的數量,然後在控制檯上取消並重新打印它,每次迭代都可以工作,但這會造成很多開銷! –