Last active
May 12, 2019 06:07
-
-
Save sgryjp/088f57ba2a0cc1948d30a55762afe660 to your computer and use it in GitHub Desktop.
Redirecting stdout into an `IOBuffer`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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