How to get a function to print stuff with REPL-like formatting

Sometimes it’s easier if what gets printed by a function looks nice (like in the REPL):

function printout(x)
    println("x is: ",x)
end

Ex 1. Beautiful formatting that can be instantly read and understood:

check = rand(2,10)
2×10 Array{Float64,2}:
 0.20608   0.675941  0.267637  0.231587  0.404712  0.628064  0.727315  0.292798  0.579271  0.00830696
 0.570077  0.440174  0.997781  0.842532  0.752924  0.360579  0.368976  0.264956  0.20852   0.166019

Ex. 2. Printing from inside a function: the first semi-colon is somewhere in there…

printout(check)
x is: [0.20607999980294323 0.6759405043446565 0.2676368465413639 0.23158728513903615 0.40471156297506106 
0.6280638109428014 0.7273151713873742 0.2927977847045118 0.5792709021856115 0.008306955592047194; 0.5700766059127313 0.4401739651076826 
0.9977809895843064 0.8425324418892446 0.7529240018391419 0.360578553537942 0.3689764314494348 0.26495555789141423 0.20851971242325895 0.1660188215790821]

How can I make printout() give me output like Ex. 1?

printout(x) = show(stdout, MIME"text/plain"(), x)
4 Likes

Thanks @sostock, sorry that my post was unclear. I meant to ask how to print an intermediate value (not the returned value) from inside a function.

This works:

function printout(x)
    display(x)
end

check = rand(2,10);

printout(check);

2×10 Array{Float64,2}:
 0.571579  0.793269  0.68453  0.732311  0.316721  0.167078  0.521398  0.830209  0.546623  0.852014
 0.98618   0.240232  0.50574  0.282009  0.329084  0.804751  0.044719  0.320697  0.735516  0.254228

Not in general. display may not output to stdout, and may not output plain text. It may open a window and display an image, for example, or use HTML display in an IJulia window. If you explicitly want text/plain output, you should use show(stdout, "text/plain", x),

2 Likes

Thanks @stevengj, MWE for reference below:

function printout(x)
    show(stdout, "text/plain", x)
end

check = rand(2,10);

printout(check);

Array{Float64,2}:
0.833317  0.0797113  0.305283  0.848721  0.897141  0.99114   0.694138  0.28158    0.82193   0.520097
0.187817  0.439049   0.922296  0.141583  0.172123  0.244657  0.720784  0.0473979  0.610638  0.941219