如何在循环运行时将 for 循环内的变量实时打印到控制台? [英] How to print a variable inside a for loop to the console in real time as the loop is running?

查看:44
本文介绍了如何在循环运行时将 for 循环内的变量实时打印到控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环,每次迭代都需要很长时间,我想实时查看它的进度.在循环运行时,如何将 for 循环内的变量实时打印到控制台?每一个都在循环完成后打印所有内容,这对我来说没用:

I have a loop that takes a long time for each iteration, and I would like to see the progress of it in real time. How do I print a variable inside a for loop to the console in real time, as the loop is running? Each of these print everything after the loop is finished, which is useless for me:

for(i in 1:10){
  write(i,stdout())
}

for(i in 1:10){
  write(i,stderr())
}

for(i in 1:10){
  print(i)
}
1
2
3
4
5
6
7
8
9
10

推荐答案

最后一个是实时打印的,试试这样:

The last one does print in real time, try it like this:

for(i in 1:10){
  Sys.sleep(0.1)
  print(i)
}

这在 Rstudio 中看起来不错,但在经典 Rgui 中,您必须单击控制台才能刷新(例如通过 Sys.sleep(0.5) 增加睡眠有助于看到这一点).您可以通过使用清除缓冲区的 flush.console 来规避:

This looks fine in Rstudio, but in classic Rgui you have to click the console in order to it to refresh (increasing the sleep for example by Sys.sleep(0.5) helps to see that). You can circumvent that by using flush.console which clears the buffer:

for(i in 1:10){
  Sys.sleep(0.1)
  print(i)
  flush.console() 
}

或者在 Windows 中,您可以选择上方工具栏中的 Misc 并取消选中 buffered output.

Or in Windows you can select Misc in the upper toolbar and uncheck the buffered output.

如果您的目标是跟踪循环的过程,那么当您运行大量迭代时,上述方法感觉有点尴尬(至少在我看来).在这种情况下,使用进度条可能会更好:

If your goal is to track the process of your loop, the above method feels bit akward (at least to my eyes) when you are running through large number of iterations. In that case it might be nicer to use progress bars:

n<- 1000
pb <- txtProgressBar(min = 0, max = n, style = 3) #text based bar
for(i in 1:n){
   Sys.sleep(0.001) 
   setTxtProgressBar(pb, i)
}
close(pb)

或者更好的东西:

library(tcltk)
n<- 1000
pb <- tkProgressBar(title = "Doing something", min = 0, max = n, width = 200)
for(i in 1:n){
   Sys.sleep(0.001) 
   setTkProgressBar(pb, i, label=paste(round(i/n*100,1),"% done"))
}
close(pb)

这篇关于如何在循环运行时将 for 循环内的变量实时打印到控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆