String 以字符串形式获取变量的Julia REPL输出
我希望得到输出,就像它作为字符串打印在juliarepl中一样,而不打印到REPL 假设您有一个大矩阵String 以字符串形式获取变量的Julia REPL输出,string,julia,read-eval-print-loop,String,Julia,Read Eval Print Loop,我希望得到输出,就像它作为字符串打印在juliarepl中一样,而不打印到REPL 假设您有一个大矩阵x x = rand(100, 100) 在REPL中,x的显示方式很好。我希望将此输出作为一个带有函数调用的字符串(不是以一种黑客的方式)。我该怎么做 我尝试使用函数repr获取输出: repr(x) 这会产生一个很长的字符串,包含所有的数字并使屏幕混乱。 我尝试使用上下文参数。 首先使用displaysize键: repr(x, context = :displaysize =>
x
x = rand(100, 100)
在REPL中,x的显示方式很好。我希望将此输出作为一个带有函数调用的字符串(不是以一种黑客的方式)。我该怎么做
我尝试使用函数repr
获取输出:
repr(x)
这会产生一个很长的字符串,包含所有的数字并使屏幕混乱。
我尝试使用上下文
参数。
首先使用displaysize
键:
repr(x, context = :displaysize => (80,80))
repr(x, context = :limit => true)
它没有任何效果。(?)
我尝试使用limit
键:
repr(x, context = :displaysize => (80,80))
repr(x, context = :limit => true)
这提供了一个输出,它不再使屏幕混乱,但它看起来不像“正常”REPL输出那么好
我用print
函数和IOContext
io = IOBuffer();
print(IOContext(io, :limit => true), x)
String(take!(io))
这与
repr
的结果相同,我想这就是您想要的:
julia> x=rand(100,100);
julia> io = IOBuffer();
julia> show(IOContext(io, :limit => true, :displaysize => (10, 10)), "text/plain", x);
julia> s = String(take!(io));
julia> println(s)
100×100 Array{Float64,2}:
0.150112 … 0.913
0.14348 0.598862
0.265236 0.378648
⋮ ⋱
0.599803 0.778466
0.79655 0.725736
julia> io = IOBuffer();
julia> show(IOContext(io, :limit => true, :displaysize => (20, 40)), "text/plain", x);
julia> s = String(take!(io));
julia> println(s)
100×100 Array{Float64,2}:
0.150112 0.998585 … 0.913
0.14348 0.754191 0.598862
0.265236 0.364718 0.378648
0.746999 0.436714 0.594933
0.247191 0.340162 0.126489
0.92214 0.518781 … 0.530581
0.483844 0.146089 0.14216
0.421205 0.401629 0.381202
⋮ ⋱
0.0944732 0.990715 0.132398
0.711658 0.958458 0.0849586
0.378591 0.518736 … 0.688399
0.77595 0.319994 0.667458
0.427935 0.375477 0.656718
0.599803 0.779445 0.778466
0.79655 0.939409 0.725736
这里有两个关键点:
- 您可以使用
并指定要使用的MIME(我想您需要show
;一般来说,例如在Jupyter笔记本内部,HTML和LaTeX用于某些类型,例如,我们在DataFrames.jl中就是这样做的,以显示REPL中给出的“text/plain”
对象)DataFrame
- 您应该设置
通常,通常:displaysize
从show
获取displaysize,但是如果您有一个自定义的stdout
,那么它不知道您可能要显示多少行和列(当然,如果您喜欢,可以使用默认值:)io