Skip to content

Commit

Permalink
Support do-block syntax for redirect_std*
Browse files Browse the repository at this point in the history
  • Loading branch information
timholy committed Aug 24, 2016
1 parent 1a19f3e commit 9789cea
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
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
17 changes: 17 additions & 0 deletions src/Compat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1452,4 +1452,21 @@ else
end
end

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

0 comments on commit 9789cea

Please sign in to comment.