Julia shell mode in a .jl file

Viewed 254

In REPL mode, Julia lets you type a semicolon and run shell commands, i.e.

;
cd ~

And then to return to Julian REPL

Is there a way to do something similar in a .jl file? The closest I found was run(…) and that has many caveats. This is a Linux environment, so I'm not concerned about the caveats of shell mode on Windows machines.

The broader topic of interest is in doing this for other REPL modes, like the R one provided by using RCall

2 Answers

You can find the code for this at https://github.com/JuliaLang/julia/tree/master/stdlib/REPL/test.

Seems there is no API, just lots of typing.

Here is a minimal working example (the codes are mostly copied from different places from the folder above):

using REPL
mutable struct FakeTerminal <: REPL.Terminals.UnixTerminal
    in_stream::Base.IO
    out_stream::Base.IO
    err_stream::Base.IO
    hascolor::Bool
    raw::Bool
    FakeTerminal(stdin,stdout,stderr,hascolor=true) =
        new(stdin,stdout,stderr,hascolor,false)
end

REPL.Terminals.hascolor(t::FakeTerminal) = t.hascolor
REPL.Terminals.raw!(t::FakeTerminal, raw::Bool) = t.raw = raw
REPL.Terminals.size(t::FakeTerminal) = (24, 80)

input = Pipe()
output = Pipe()
err = Pipe()
Base.link_pipe!(input, reader_supports_async=true, writer_supports_async=true)
Base.link_pipe!(output, reader_supports_async=true, writer_supports_async=true)
Base.link_pipe!(err, reader_supports_async=true, writer_supports_async=true)
repl = REPL.LineEditREPL(FakeTerminal(input.out, output.in, err.in, false), false)

repltask = @async REPL.run_repl(repl)

Now you can do:

julia> println(input,";ls -la *.jld2")

-rw-r--r-- 1 pszufe 197121 5506 Jul  5  2020 file.jld2
-rw-r--r-- 1 pszufe 197121 5506 Jul  5  2020 myfile.jld2
Related