Is there a function for printing the REPL content to a file in Julia language?

Viewed 893

I already have output some content in the REPL. Is there any function to print all this content to a file?

3 Answers

If those outputs have already been printed in the REPL, I guess the only way to save them to a file is copy-pasting manually. But if you would like to save the REPL output history for future use, one way is to overload display:

shell> touch repl_history.txt

julia> using REPL

julia> function REPL.display(d::REPL.REPLDisplay, mime::MIME"text/plain", x)
           io = REPL.outstream(d.repl)
           get(io, :color, false) && write(io, REPL.answer_color(d.repl))
           if isdefined(d.repl, :options) && isdefined(d.repl.options, :iocontext)
               # this can override the :limit property set initially
               io = foldl(IOContext, d.repl.options.iocontext,
                          init=IOContext(io, :limit => true, :module => Main))
           end
           show(io, mime, x)
           println(io)
           open("repl_history.txt", "a") do f
              show(f, mime, x)
              println(f)
           end
           nothing
       end

then, let's print something random in the REPL:

julia> rand(10)
10-element Array{Float64,1}:
 0.37537591915616497
 0.9478991508737484 
 0.32628512501942475
 0.8888960925262224 
 0.9967927432272801 
 0.4910769590205608 
 0.7624517049991089 
 0.26310423494973545
 0.5117608425961135 
 0.0762255311602309 

help?> gcd
search: gcd gcdx significand

  gcd(x,y)

  Greatest common (positive) divisor (or zero if x and y are both zero).

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> gcd(6,9)
  3

  julia> gcd(6,-9)
  3

And here is what the file content looks like:

shell> cat repl_history.txt
10-element Array{Float64,1}:
 0.37537591915616497
 0.9478991508737484 
 0.32628512501942475
 0.8888960925262224 
 0.9967927432272801 
 0.4910769590205608 
 0.7624517049991089 
 0.26310423494973545
 0.5117608425961135 
 0.0762255311602309 
  gcd(x,y)

  Greatest common (positive) divisor (or zero if x and y are both zero).

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> gcd(6,9)
  3

  julia> gcd(6,-9)
  3

If there is no need to work with REPL interactively, simply use julia script.jl > output.txt might also do the trick.

What you've printed isn't saved anywhere, so no, there's no way to do that. It may be that there's something easy to do but without more details it's impossible to way really.

If you want to save variables to file, you can you JLD2 package. Then you can save each variable as below:

    using JLD2, FileIO
    hello = "world"
    foo = :bar
    @save "example.jld2" hello foo
Related