jupyter-notebookjuliaijulia-notebook

Is there a way to suppress outputs inside a function in a Julia Jupyter notebook?


In a Jupyter cell, I'd like to call a function that has some println, @show, etc in it, but I don't want to see those outputs. Is there a way to call a function while suppressing outputs? I'm aware of ;, but my understanding is that ; only affects the return value.

For example, let's say you have a function

function testOutputs()
    @show("Show macro still showing")
    println("Println still showing")
    a = 1 + 2
end

Calling testOutputs(); in a cell results in:

"Show macro still showing" = "Show macro still showing"
Println still showing

I would like it to print nothing.


Solution

  • As phyatt's answer highlights it would often be better for library code to use a configurable logging mechanism. However, sometimes you want to call code that, for whatever reason, writes directly to stdout. One way to handle these cases is to use redirect_stdout.

    For example:

    real_stdout = stdout
    (rd, wr) = redirect_stdout();
    # Noisy code here
    redirect_stdout(real_stdout)
    

    You'd probably want to put this in a function or a macro or simply use Suppressor.jl a library that provides these macros. If you want to capture the output the way the ipython %%capture magic does you can have a look at @capture_out in Suppressor.jl, this SO question and this forum thread.