Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support do-block syntax for redirect_std* #275

Merged
merged 1 commit into from
Aug 25, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ Currently, the `@compat` macro supports the following syntaxes:

* [`normalize`](http://docs.julialang.org/en/latest/stdlib/linalg/?highlight=normalize#Base.normalize) and [`normalize!`](http://docs.julialang.org/en/latest/stdlib/linalg/?highlight=normalize#Base.normalize!), normalizes a vector with respect to the p-norm ([#13681](https://github.com/JuliaLang/julia/pull/13681))

* `redirect_stdout`, `redirect_stderr`, and `redirect_stdin` take an optional function as a first argument, `redirect_std*(f, stream)`, so that one may use `do` block syntax (as first available for Julia 0.6).

## Renamed functions

* `pointer_to_array` and `pointer_to_string` have been replaced with `unsafe_wrap(Array, ...)` and `unsafe_wrap(String, ...)` respectively.
Expand Down
11 changes: 11 additions & 0 deletions src/Compat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1452,4 +1452,15 @@ else
end
end

import Base: redirect_stdin, redirect_stdout, redirect_stderr
if VERSION < v"0.6.0-dev.374"
for (F,S) in ((:redirect_stdin, :STDIN), (:redirect_stdout, :STDOUT), (:redirect_stderr, :STDERR))
@eval function $F(f::Function, stream)
STDOLD = $S
$F(stream)
try f() finally $F(STDOLD) end
end
end
end

end # module
27 changes: 27 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1354,3 +1354,30 @@ let n=5, a=rand(n), incx=1, b=rand(n), incy=1
&n, a, &incx, b, &incy)
@test a == b
end

# do-block redirect_std*
let filename = tempname()
ret = open(filename, "w") do f
redirect_stdout(f) do
println("hello")
[1,3]
end
end
@test ret == [1,3]
@test chomp(readstring(filename)) == "hello"
ret = open(filename, "w") do f
redirect_stderr(f) do
warn("hello")
[2]
end
end
@test ret == [2]
@test contains(readstring(filename), "WARNING: hello")
ret = open(filename) do f
redirect_stdin(f) do
readline()
end
end
@test contains(ret, "WARNING: hello")
rm(filename)
end