Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ See the docstring for full documentation.

## Known limitations

### Separately stored `stdout` or `stderr` objects

The capturing does not work properly if `f` prints to the `stdout` object that has been
stored in a separate variable or object, e.g.:

Expand Down Expand Up @@ -56,6 +58,17 @@ Stacktrace:
This is because `stdout` and `stderr` within an `iocapture` actually refer to the temporary
redirect streams which get cleaned up at the end of the `iocapture` call.

### ANSI color/escape code

On Julia v1.6 and later, the captured output of `iocapture` inherits the `:color` property
of the `stdout` or `stderr` by default. The colorization can be disabled by setting the
`color` keyword argument of `iocapture` to `false`.

On the other hand, on Julia v1.5 or earlier, even if the `color` keyword argument is set to
`true`, no coloring will be applied. However, this limitation might be removed in the
future, so you should specify `color=false` if you want to avoid coloring.


## Similar packages

* [Suppressor.jl](https://github.com/JuliaIO/Suppressor.jl) provides similar functionality,
Expand Down
21 changes: 16 additions & 5 deletions src/IOCapture.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ using Logging
export iocapture

"""
iocapture(f; throwerrors=true)
iocapture(f; throwerrors=true, color=true)

Runs the function `f` and captures the `stdout` and `stderr` outputs without printing them
in the terminal. Returns an object with the following fields:
Expand All @@ -21,6 +21,10 @@ The behaviour can be customized with the following keyword arguments:
via the `.value` field (with also `.error` and `.backtrace` set accordingly). If set to
`:interrupt`, only `InterruptException`s are rethrown.

* `color`: if set to `true` (default), `iocapture` inherits the `:color` property of
`stdout` and `stderr`, which specifies whether ANSI color/escape codes are expected. This
argument is only effective on Julia v1.6 and later.

# Extended help

`iocapture` works by temporarily redirecting the standard output and error streams
Expand Down Expand Up @@ -49,7 +53,7 @@ It is also possible to set `throwerrors = :interrupt`, which will make `iocaptur
only `InterruptException`s. This is useful when you want to capture all the exceptions, but
allow the user to interrupt the running code with `Ctrl+C`.
"""
function iocapture(f; throwerrors::Union{Bool,Symbol}=true)
function iocapture(f; throwerrors::Union{Bool,Symbol}=true, color::Bool=true)
# Currently, :interrupt is the only valid Symbol value for throwerrors
if isa(throwerrors, Symbol) && throwerrors !== :interrupt
throw(DomainError(throwerrors, "Invalid value passed for throwerrors"))
Expand All @@ -62,10 +66,17 @@ function iocapture(f; throwerrors::Union{Bool,Symbol}=true)
# Redirect both the `stdout` and `stderr` streams to a single `Pipe` object.
pipe = Pipe()
Base.link_pipe!(pipe; reader_supports_async = true, writer_supports_async = true)
redirect_stdout(pipe.in)
redirect_stderr(pipe.in)
if VERSION >= v"1.6.0-DEV.481" # https://github.com/JuliaLang/julia/pull/36688
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth sticking a @static in here to avoid the runtime branch?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm skeptical that there is a runtime branch, but I'll stick the @static to be clear.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, looks like it's smart enough these days:

julia> function f(x, y)
           if VERSION >= v"1.4.0"
               x + y
           else
               x - y
           end
       end

julia> @code_typed f(1, 2)
CodeInfo(
1 ─ %1 = Base.add_int(x, y)::Int64
└──      return %1
) => Int64

No point adding @static then.

pe_stdout = IOContext(pipe.in, :color => get(stdout, :color, false) & color)
pe_stderr = IOContext(pipe.in, :color => get(stdout, :color, false) & color)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be get(stderr, ...)?

else
pe_stdout = pipe.in
pe_stderr = pipe.in
end
redirect_stdout(pe_stdout)
redirect_stderr(pe_stderr)
# Also redirect logging stream to the same pipe
logger = ConsoleLogger(pipe.in)
logger = ConsoleLogger(pe_stderr)

# Bytes written to the `pipe` are captured in `output` and converted to a `String`.
output = UInt8[]
Expand Down
25 changes: 22 additions & 3 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ using Test
# Note: this can not be inside the testset
(VERSION < v"1.2.0-DEV.272") && (hasfield(::Type{T}, name::Symbol) where T = Base.fieldindex(T, name, false) > 0)

hascolor(io) = VERSION >= v"1.6.0-DEV.481" && get(io, :color, false)
has_escapecodes(s) = occursin(r"\e\[[^m]*m", s)
strip_escapecodes(s) = replace(s, r"\e\[[^m]*m" => "")

# Callable object for testing
struct Foo
x
Expand Down Expand Up @@ -61,13 +65,25 @@ end
@test c.value === nothing

# Colors get discarded
c = iocapture() do
c = iocapture(color=false) do
printstyled("foo", color=:red)
end
@test !c.error
@test c.output == "foo"
@test c.value === nothing

# Colors are preserved if it's supported
c = iocapture() do
printstyled("foo", color=:red)
end
@test !c.error
if hascolor(stdout)
@test c.output == "\e[31mfoo\e[39m"
else
@test c.output == "foo"
end
@test c.value === nothing

# This test checks that deprecation warnings are captured correctly
c = iocapture() do
println("println")
Expand All @@ -83,9 +99,12 @@ end
@test isdefined(Base, :JLOptions)
@test hasfield(Base.JLOptions, :depwarn)
if Base.JLOptions().depwarn == 0 # --depwarn=no, default on Julia >= 1.5
@test c.output == "println\n[ Info: @info\n"
@test has_escapecodes(c.output) === hascolor(stderr)
@test strip_escapecodes(c.output) == "println\n[ Info: @info\n"
else # --depwarn=yes
@test startswith(c.output, "println\n[ Info: @info\n┌ Warning: depwarn\n")
@test has_escapecodes(c.output) === hascolor(stderr)
output_nocol = strip_escapecodes(c.output)
@test startswith(output_nocol, "println\n[ Info: @info\n┌ Warning: depwarn\n")
end

# Exceptions -- normally rethrown
Expand Down