pythonrreticulateconsole-output

reticulate doesn't print to console in real time


Using Python's print() (or to the best of my knowledge, any other console output generating) function in loop structures and running the code via reticulate in R, the output is only printed after the execution finished. For example, take the following loop which goes to sleep for 1.5 seconds after each iteration; the run numbers are all printed in one go after the loop is through. The same applies when saving the Python code to a separate .py file and then running reticulate::py_run_file().

library(reticulate)

py_run_string("
import time

for i in range(5):
   print(str(i))
   time.sleep(1.5) # sleep for 1.5 sec
")

Does anyone know where this behavior comes from and, if possible, how to circumvent it?


Solution

  • Apparently, you need to force pyhton to export the standard output at times. You can do this by adding sys.stdout.flush() to your code:

    library(reticulate)
    
    py_run_string("
    import time
    import sys
    
    for i in range(5):
       print(str(i))
       time.sleep(1.5) # sleep for 1.5 sec
       sys.stdout.flush()
    ")
    

    see over here described with nohup