【问题标题】:Is there a function for printing the REPL content to a file in Julia language?是否有将 REPL 内容打印到 Julia 语言文件的功能?
【发布时间】:2020-06-26 08:24:01
【问题描述】:

我已经在 REPL 中输出了一些内容。是否有任何功能可以将所有这些内容打印到文件中?

【问题讨论】:

    标签: julia read-eval-print-loop


    【解决方案1】:

    如果这些输出已经打印在 REPL 中,我想将它们保存到文件的唯一方法是手动复制粘贴。但是如果你想保存 REPL 输出历史以备将来使用,一种方法是重载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
    

    然后,让我们在 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
    

    这是文件内容的样子:

    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
    

    如果不需要以交互方式使用 REPL,只需使用 julia script.jl > output.txt 也可以解决问题。

    【讨论】:

    • 非常感谢您的详细回答。我试过第一个,它可以工作。对于第二个,似乎“>”无法重定向 Julia 中的输出。第一个就够了。再次感谢。
    【解决方案2】:

    您打印的内容没有保存在任何地方,所以不,没有办法做到这一点。可能有些事情很容易做,但没有更多细节就不可能真正做到。

    【讨论】:

    【解决方案3】:

    如果你想将变量保存到文件中,你可以JLD2 package。然后您可以将每个变量保存如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多