function switch(s)
if s == :on
doit[1] = true
rd = redirect_stderr()[1]
@async while doit[1]
println("Test: ", readline(rd))
end
elseif s == :off
doit[1] = false
println(stderr, s) # solution: give it something to read !!
redirect_stderr(old_stderr)
else
println(stderr, "not allowed: $s")
end
end
then you can do (needs still 2 global variables):
julia> old_stderr = stderr
Base.TTY(RawFD(22) open, 0 bytes waiting)
julia> doit = [false];
julia> t = switch(:on)
Task (runnable) @0x000000016704f860
julia> println(stderr, "test 1")
Test: test 1
julia> println(stderr, "test 2")
Test: test 2
julia> switch(:off)
Test: off
Base.TTY(RawFD(22) open, 0 bytes waiting)
julia> println(stderr, "test 3")
test 3
julia> t
Task (done) @0x000000016704f860
the following doesnโt need even global old_stderr. We capture stderr when we switch on and let the task itself restore it.
function switch3(s)
my_switch = "sloBMBS90eXNG"
if s == :on
if stderr isa Base.TTY
old_stderr = stderr
rd = redirect_stderr()[1]
@async while true
line = readline(rd)
line != my_switch ?
println("Test3: ", line) :
(redirect_stderr(old_stderr); break)
end
end
elseif s == :off
println(stderr, my_switch)
else
println(stderr, "not allowed: $s")
end
end
julia> t = switch3(:on)
Task (runnable) @0x000000011331f640
julia> println(stderr, "test 1")
Test3: test 1
julia> switch3(:off)
julia> println(stderr, "test 2")
test 2
julia> t
Task (done) @0x000000011331f640