Just a little bump. Since I had no answer here, I cross-posted to SO, where I had a great answer. However, I still don’t get all the subtleties of Julia I/O…
My real goal is to retrieve external code blocks (without modifying them) and automatically redirect their REPL output to a given file. You’ll understand that I need thus a universal solution, which will work for any type of output (dataframe, dict, tuple, array, etc.). This sounds like a very basic task, but I really can’t find any universal solution in Julia, which sounds just absurd to me.
Let’s say I have the following code block:
x = [1, 2, 3, 4]
for i=1:3
println(x[i])
end
Everyone can guess waht would be the REPL output. I would just need that this classical REPL output of such a code block could be written as is, into a file.
- First try:
open("/home/fsantos/myfile.txt", "w") do io
show(io, "text/plain", begin
x = [1, 2, 3, 4]
for i=1:3
println(x[i])
end
end)
end
This creates a file where it’s only written… nothing
. The loop result 1 2 3
is still printed in the REPL only, and x
is not displayed at all (neither in the file nor in the REPL). What’s the reason for that?
- Second try: with the
@capture_out
macro from Suppressor.jl, with or without wrapping the whole code block within a print
instruction. I let you see that none of those two options universally capture the real REPL output of those very elementary code blocks: sometimes you need a print
, sometimes you don’t need it, but there seems to be no means of guessing whether it’s necessary or not. And none of those solutions is really satisfying:
using Suppressor
output = @capture_out begin
x = [1, 2, 3, 4]
end
output # doesnt' work at all
output = @capture_out print(begin
x = [1, 2, 3, 4]
end)
output # works, but with a different style than in the REPL
output = @capture_out begin
for i=1:3
println(i)
end
end
output # works
output = @capture_out print(begin
for i=1:3
println(i)
end
end)
output # adds a "nothing" row (why?..)
In R, there’s just the very simple function sink()
to write very easily any REPL output into a file. It looks like there’s no solution at all in Julia for such a basic task?..