Skip to content

Instantly share code, notes, and snippets.

@sgryjp
Last active May 12, 2019 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgryjp/088f57ba2a0cc1948d30a55762afe660 to your computer and use it in GitHub Desktop.
Save sgryjp/088f57ba2a0cc1948d30a55762afe660 to your computer and use it in GitHub Desktop.
Redirecting stdout into an `IOBuffer`
"""
redirect_stdout(f::Function, stream::IOBuffer)
```julia
julia> buf = IOBuffer();
julia> redirect_stdout(buf) do
print("Hello, World!")
end
julia> String(take!(buf))
"Hello, World!"
```
"""
function Base.redirect_stdout(f::Function, stream::IOBuffer)
backup = stdout
rd, wr = redirect_stdout()
try
f()
finally
redirect_stdout(backup)
close(wr)
write(stream, read(rd))
close(rd)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment