Julia:哪个环境 variable/setting 控制 repl 中为数组打印的元素数量?

Julia: which environment variable/setting controls the number of elements printed for an array in the repl?

当我打印时

rand(1_000_000)

它打印前 N 行并打印最后 N 行。 N 是如何确定的,我该如何控制 N

大小由 Base.displaysize(::IO) 计算得出,您可以看到应该报告 stdout 的终端大小,并报告 IOBuffers 的 "standard" 大小:

julia> Base.displaysize(stdout)
(19, 81)


julia> Base.displaysize(IOBuffer())
(24, 80)

julia> Base.displaysize()
(24, 80)

这是在完整的 show() 方法中调用的,用于在 REPL 中显示数组: show(io::IO, ::MIME"text/plain", X::AbstractArray),在 print_matrix 内,这里:

    if !get(io, :limit, false)
        screenheight = screenwidth = typemax(Int)
    else
        sz = displaysize(io)
        screenheight, screenwidth = sz[1] - 4, sz[2]
    end

https://github.com/NHDaly/julia/blob/879fef402835c1727aac52bafae686b5913aec2d/base/arrayshow.jl#L159-L164

请注意,虽然在那个函数中,io 实际上是一个 IOContext,所以正如@Fengyang Wang 在这个答案中描述的那样:,您也可以手动设置 displaysize 在 IOContext 上,如果你想自己控制它(为 julia 1.0 更新):

julia> show(IOContext(stdout, :limit=>true, :displaysize=>(10,10)), MIME("text/plain"), rand(1_000_000))
1000000-element Array{Float64,1}:
 0.5684598962187111
 0.2779754727011845
 0.22165656934386813
 ⋮
 0.3574516963850929
 0.914975294703998

最后,关闭循环,在 REPL 中显示一个值变成 show(io, MIME("text/plain"), v),通过 displayhttps://github.com/NHDaly/julia/blob/879fef402835c1727aac52bafae686b5913aec2d/base/multimedia.jl#L319

如果您希望设置在您的 REPL 会话中保留:

Base.active_repl.options.iocontext[:displaysize] = (100, 80)

这将告诉 Julia 使用 100 行和 80 列。您可以返回默认值:

Base.active_repl.options.iocontext[:displaysize] = displaysize(stdout)

要更改对 show 的单个调用的显示大小,您可以按照其他人的建议进行操作:

show(IOContext(stdout, :limit=>true, :displaysize=>(100,80)),
     MIME("text/plain"),
     thing)