Reputation: 30184
In R, capture.output()
can capture the output to stdout
in an expression as a character vector, e.g.
> x = capture.output(print(1:10))
> x
[1] " [1] 1 2 3 4 5 6 7 8 9 10"
Is there an equivalent function in Julia?
Upvotes: 11
Views: 2834
Reputation: 441
With Julia 0.2, there is now a way to capture standard output: you can call redirect_stdout to convert STDOUT
into a pipe that you can read from.
This is mainly useful to capture output from external C libraries. As Stefan mentioned, most Julia I/O functions accept an io
argument that allows you to print to an arbitrary destination, such as a string buffer.
Upvotes: 7
Reputation: 5700
Not sure what you are after, but if you are trying to bring knitr
to julia
then awesome!
The Gadfly package has weave, which does some of this.
Check out https://github.com/dcjones/Gadfly.jl/blob/master/src/weave.jl#L19
and
https://github.com/dcjones/Gadfly.jl/blob/master/src/weave.jl#L423
I've been using it in https://github.com/jverzani/Weave.jl to make self-grading quizzes from markdown.
Upvotes: 3
Reputation: 33290
Standard library functions should all accept an optional IO-typed first argument that will be printed to if provided but otherwise will default to STDOUT. In that case, you can use sprint(io->f(io,...))
to capture what's printed to a string. If the functions haven't been written to print to a given IO object, then there isn't a way to redirect the output.
Upvotes: 4