diff --git a/README.md b/README.md index d71054c4b..39709bbc1 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/src/Compat.jl b/src/Compat.jl index ab87e94c0..9bd8f0804 100644 --- a/src/Compat.jl +++ b/src/Compat.jl @@ -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 diff --git a/test/runtests.jl b/test/runtests.jl index fadf171b6..5cd9891aa 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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