使用 IJulia-notebook 时避免输出截断的最佳方法

Best way to avoid output truncation when using IJulia-notebook

从来源我可以看到 IJulia

Truncate the output to max_output_per_request bytes per execution request since excessive output can bring browsers to a grinding halt.

我也同意在交互部分打印很长的内容不一定有用,但有时我想打印只需要一行的信息来跟踪进度。

IJulia 使用 stdio_bytes:

跟踪写入的字节数
using IJulia

N = 10_000
slen = 100

println("\nPrinting ", N, " lines")
for i in 1:N
    IJulia_counter = IJulia.stdio_bytes[]; # IJulia byte counter
    print(rpad(string("line: ", i, ", iJulia counter: " , IJulia_counter), slen), "\r")
    mod(i, 50) == 0 && flush(stdout) # just forcing to print
    IJulia_counter > 524000 && flush(stdout)
end
flush(stdout)
# Final output
# Printing 10000 lines
# line: 5190, iJulia counter: 524089    
# Excessive output truncated after 524291 bytes.

我目前正在通过手动重置此计数器来解决问题

println("\nPrinting $N lines")
for i in 1:N
    IJulia_counter = IJulia.stdio_bytes[]; # IJulia byte counter
    print(rpad(string("line: ", i, ", iJulia counter: " , IJulia_counter), slen), "\r")
    mod(i, 50) == 0 && flush(stdout) # just forcing to print
    IJulia_counter > 524000 && (IJulia.stdio_bytes[] = 0) # Reset counter
end
flush(stdout)
# Final output
# Printing 10000 lines
# line: 10000, iJulia counter: 485810   

解决此问题的最佳方法是什么?是否可以进行任何外部配置?我不想导入 IJulia 只是为了防止在交互部分出现这种情况。

谢谢!!!

您需要添加:

if isdefined(Main, :IJulia)
    Main.IJulia.stdio_bytes[] = 0
end

这可以避免 I/O 在加载 IJulia 时 IJulia 进行节流,否则将被忽略(因此如果不需要 IJulia,则不必加载它)。此推荐基于其代码:https://github.com/stevengj/ProgressMeter.jl/commit/4bfc3e5a7e4ea889022ba704e741f3b8eaca0752 所以这可能是您能得到的最好的。

完整示例代码:

using IJulia

N = 10_000
slen = 100

println("\nPrinting ", N, " lines")
for i in 1:N
    print(rpad(string("line: ", i ), slen), "\r")
    if mod(i, 50) == 0 
        flush(stdout) # just forcing to print
        if isdefined(Main, :IJulia)
            Main.IJulia.stdio_bytes[] = 0
        end
    end
end
flush(stdout)

我建议您也尝试考虑 ProgressMeter.jl 来监控您的进度:

using ProgressMeter
N=10000
p = Progress(N, 0.1)
for i in 1:N
    next!(p)
    rand(100_000) #added so something is happening here
end