Jupyter notebook capture stdout and stderr like python capture magic?

Hi,
in Jupyter one can use the python %%capture magic to redirect stdout, stderr into a variable. How do you do that in Julia with Juypter? I, most of the times, only have a pure Julia kernel running.

Maybe as a bonus: Is there a way to “tie” the output to a specific cell as well? I want to run asynchronous tasks and if I switch cells, they start to write into the standard output of other cells, which is somehow annoying :smiley:

Julia has built-in redirect_stdout /redirect_stderr. Do they suit your needs?

https://docs.julialang.org/en/v1/base/io-network/index.html#Base.redirect_stdout

I do not know how they work together with jupyter. I do not want to redirect ALL output, just the output of some code running in specific cells in a jupyter notebook.
Does anyone know, how that would be done?

let old_stdout = stdout
    rd, = redirect_stdout()
    try
        println("This output is redirected.\n")
    finally
        redirect_stdout(old_stdout) # restore original stdout
    end
    output = String(readavailable(rd))
    println("captured the output: ", output)
end
3 Likes

This looks promising! I will give this a try as soon as I can!

It’s harder than it should be, though. We should really have a capture_stdout() function in the standard library, so that you can do:

data = capture_stdout() do
    ...
end
String(data)

or similar. Or maybe

buf = IOBuffer()
redirect_stdout(buf) do
    ...
end
String(take!(buf))

See

4 Likes

That would be very nice! Especially if you want to hack something quickly together in a notebook :slight_smile:

https://github.com/JuliaIO/Suppressor.jl has an @capture_out macro, but in a Jupyter notebook cell it appeared to freeze forever for me with Julia 1.1.1,

Can you file an issue with Suppressor.jl?

1 Like

I see you don’t pronounce the ‘at’ :slightly_smiling_face:. I opened @capture_out hangs in Jupyter notebooks · Issue #31 · JuliaIO/Suppressor.jl · GitHub.

1 Like

See also More convenient redirect_* methods · Issue #28679 · JuliaLang/julia · GitHub.

1 Like