Writing file inside a loop

Hi there!
I’m running some stuff in a cluster… Due to this take long time calculations I would like to follow some kind of output file to know how it is going… It seems that inside a loop the output file is not modified step by step, on the contrary the entire file is written at the end of the loop.

Here an basic example:

f = open(“geek.txt”, “w”)
for i=1:10
sleep(3)
println(f, “$i\n”)
end
close(f)

Any idea how I can follow the execution in long time calculations?

Thanks in advance!
Best,
Crist.

The stream is buffered so you need to call flush(f) if you want the bytes to be written directly.

open("f.txt", "w") do f
    for i = 1:10
        sleep(3)
        println(f, i)
        flush(f)
    end
end
4 Likes

You should flush it from time to time.

As a side note, is better to use logging system to do this kind of stuff, then you’ll be able to modify your output and turn on and off parts of output, without modifying the code.

LoggingExtras.jl should be really helpful.

3 Likes

Thank you!

Thank you! I will take a look to this package.

1 Like