How can I run a file and obtain the results in the screen as if the file were executed line by line in the REPL? For example, if I have the file “file.jl”:
socat can simulate tty input for any process:
run echo 'a = 2\nb = 3\nc = a + b' | socat - EXEC:'julia',pty,setsid
or cat file.jl | socat - EXEC:'julia',pty,setsid
a = 1
b = 1
function mysum(u, v)
u + v
end
mysum(a, b)
We can define two functions
function repl_show(s::AbstractString)
block = Meta.parse(s)
args = block.args
expressions = filter(x -> typeof(x) != LineNumberNode, args)
for ex in expressions
code = string(ex)
println("julia> $code")
out = eval(ex)
println("$out\n")
end
end
function repl_file(path)
contents = read(path, String)
s = """
begin
$contents
end
"""
repl_show(s)
end
and apply them to the file:
julia> repl_file("file.jl")
which gives as output
julia> a = 1
1
julia> b = 1
1
julia> function mysum(u, v)
#= none:4 =#
#= none:5 =#
u + v
end
mysum
julia> mysum(a, b)
2
To “carry” these tools around across various folders or projects, you can put repl_show and repl_file in a package like ShowREPL. Then, it can be used as
julia -e 'using ShowREPL; ShowREPL.repl_file("file.jl")' > output.txt