From 2c11855a34bd2a9e277f5ddbec8eed49df48a02b Mon Sep 17 00:00:00 2001 From: Tim Holy Date: Thu, 25 Aug 2016 12:35:59 -0500 Subject: [PATCH] Support do-block syntax for redirect_std* --- README.md | 2 ++ src/Compat.jl | 11 +++++++++++ test/runtests.jl | 27 +++++++++++++++++++++++++++ 3 files changed, 40 insertions(+) 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..8fbcce5e7 100644 --- a/src/Compat.jl +++ b/src/Compat.jl @@ -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 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