Get Julia REPL output of variable as a string

Viewed 709

I would like to get the output like it is printed in the Julia REPL as a string, without printing to a REPL.

Consider you have a large matrix x.

x = rand(100, 100)

In the REPL, x is displayed in a nice way. I would like to get this output as a string with a function call (not in a hacky way). How can I do this?

I tried to use the function repr to get the output:

repr(x)

This gives a very long string, containing all the numbers and cluttering the screen. I tried to use the context argument. At first with the displaysize key:

repr(x, context = :displaysize => (80,80))

It doesn't have any effect. (?) I try to use the limit key:

repr(x, context = :limit => true)

This gives an output which doesn't clutter the screen any more but it doesn't look as nice as the "normal" REPL output.

I tried the same with the print function and an IOContext

io = IOBuffer();
print(IOContext(io, :limit => true), x)
String(take!(io))

This gives the same result as repr.

1 Answers

I guess this is what you want:

julia> x=rand(100,100);

julia> io = IOBuffer();

julia> show(IOContext(io, :limit => true, :displaysize => (10, 10)), "text/plain", x);

julia> s = String(take!(io));

julia> println(s)
100×100 Array{Float64,2}:
 0.150112  …  0.913
 0.14348      0.598862
 0.265236     0.378648
 ⋮         ⋱
 0.599803     0.778466
 0.79655      0.725736

julia> io = IOBuffer();

julia> show(IOContext(io, :limit => true, :displaysize => (20, 40)), "text/plain", x);

julia> s = String(take!(io));

julia> println(s)
100×100 Array{Float64,2}:
 0.150112   0.998585  …  0.913
 0.14348    0.754191     0.598862
 0.265236   0.364718     0.378648
 0.746999   0.436714     0.594933
 0.247191   0.340162     0.126489
 0.92214    0.518781  …  0.530581
 0.483844   0.146089     0.14216
 0.421205   0.401629     0.381202
 ⋮                    ⋱
 0.0944732  0.990715     0.132398
 0.711658   0.958458     0.0849586
 0.378591   0.518736  …  0.688399
 0.77595    0.319994     0.667458
 0.427935   0.375477     0.656718
 0.599803   0.779445     0.778466
 0.79655    0.939409     0.725736

The two key things here are:

  • you use show and specify MIME you want to use (I guess you want "text/plain" which is given in REPL; in general e.g. in Jupyter Notebook internally HTML and LaTeX are used for some types, e.g. this is what we do in DataFrames.jl to show DataFrame objects)
  • you should set :displaysize in general also, normally show gets displaysize from stdout, but if you have a custom io then it does not know how many lines and columns you might want to show (of course you can stick to the default values if you like them :))
Related