How to redirect to "nothing" the standard output of a function I call?

I have a function that prints some stuff I don’t need (the IPOPT licence… the problem is that this is in a long loop…).

How do I specify, when I call function foo() that I want its standard output stream to be redirected to /dev/null or whatever ?

EDIT:
I did found this, however I don’t know if it is portable, i.e. if it works only in Linux/Mac or also in Windows:

oldstd = stdout
redirect_stdout(open("/dev/null", "w"))
foo()
redirect_stdout(oldstd) # recover original stdout

if foo doesn’t have arguments one can use also redirect_stdout(foo, open("/dev/null", "w"))

EDIT2:
I did found that also redirect_stdout(open("nul", "w")) works on linux, and as it is claimed that it works on Windows, this should be an OS independent way to go to suppress output, right ?

Maybe somthing like this?!

function ohne_print(print_function::Expr) 
    open("nul","w") do muell
        oldstd = stdout;
        redirect_stdout(muell);
        eval(print_function);
        redirect_stdout(oldstd);
    end
    return
end
1 Like
help?> devnull
search: devnull

  devnull


  Used in a stream redirect to discard all data written to it. Essentially equivalent to /dev/null on Unix or NUL on Windows.
  Usage:
4 Likes

Putting the last two answers together more concisely…

redirect_stdout(devnull) do ... end

EDIT: Should have tested it, it does not work :frowning_face:. This does:

redirect_stdout(open(tempname(), "w")) do; println(1) end

although it’s clearly suboptimal. I’d love to get an answer to this question

2 Likes

Good to know! Link to the docs for completeness: I/O and Network · The Julia Language

One thing which is not clear from the docs is: what happens to return value of f? Hopefully this is returned by redirect_stdout