Run file and print line results as in REPL

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”:

a = 1
b = 1
c = a+b

and run it from the shell

~$ julia file.jl > output.txt

the file output.txt should contain:

julia> a = 1
2
julia> b = 2
3
julia> c = a+b
5
1 Like

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

Just to check: should it be line by line or expression by expression. For example, would the following also be a valid file.jl?

a = 1
b = 1
c = a+b
function mysum(u, v)
    u + v
end
mysum(a, b)

Actually, by expression.

Say file.jl contains

 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
3 Likes