Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flush the print buffer in R?

Tags:

r

I want to run a long-running simulation and have updates printed periodically. However, I am finding that my print statements are being buffered, even when I explicitly try to flush. Here, for example:

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

I would expect this to increment every 1sec, but it outputs everything at the end, after 10 seconds.

How would you force a flush of the print buffer?

like image 630
Paul Raff Avatar asked Jul 04 '17 20:07

Paul Raff


People also ask

How do I flush printf buffer?

If you need to see the output, you need to make sure the buffer is flushed. You can do this for an _IOLBF stream by making sure to end each printf format string with a '\n' (new line). Since the stdout stream is line buffered this will cause the buffer to be flushed.

How do you flush a buffer?

The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set.

What does flush true do in print?

flush=False (yes, the default) will wait for the line to complete before printing it. flush=True will force our terminal to print it. flush does not matter if end=\n .

How do you flush a buffer in Python?

File flush() method in Python. The flush() method in Python file handling clears the internal buffer of the file. In Python, files are automatically flushed while closing them. However, a programmer can flush a file before closing it by using the flush() method.


2 Answers

I usually do it like this:

for (i in 1:10) {
    message(i,"\r",appendLF=FALSE)
    flush.console()
    Sys.sleep(1)
}
like image 63
psychOle Avatar answered Sep 21 '22 11:09

psychOle


You can also use cat():

for (i in 1:10) {

  # Sleep for 1 second
  Sys.sleep(1)

  # Print the current iteration
  cat(paste0("\r", i))      
}
like image 30
Joseph Crispell Avatar answered Sep 19 '22 11:09

Joseph Crispell