As you know I think there are two things to distinguish:
- Output generated by your code
- Output generated by the REPL functions
The code
dtf = DataFrame(a=1:5)
dtf
generates no output. But if you type it in the REPL, your are executing another piece of code: a REPL function that evaluates your code and prints the result.
If you want to redirect output from your code, you can use Suppressor.jl, or simply something like this:
julia> open("stdout.txt", "w") do io
redirect_stdout(io) do
println("Hello")
end
end
But I don’t know if it’s possible to redirect output generated by the REPL. For that I would pipe the script to a new Julia process, so I can redirect the output from the shell.
For example, say I have a file a.jl
containing the following:
using DataFrames
dtf = DataFrame([8.04 9.14 7.46 6.58
6.95 8.14 6.77 5.76
8.33 9.26 7.81 8.47], :auto)
x = 3
If I run julia a.jl
in the terminal, I get no output because the code runs without a REPL and generates no output.
However on Linux for example I can run it by calling julia <a.jl >stdout.txt
: this feeds the code through standard input. Apparently this is enough to make Julia start a REPL, so it prints results as you want. And the shell redirects the results to stdout.txt
:
cat stdout.txt
3×4 DataFrame
Row │ x1 x2 x3 x4
│ Float64 Float64 Float64 Float64
─────┼────────────────────────────────────
1 │ 8.04 9.14 7.46 6.58
2 │ 6.95 8.14 6.77 5.76
3 │ 8.33 9.26 7.81 8.47
3
To redirect both stdout and stderr, you could use julia >output.txt 2>&1
, or with a recent Bash version: julia &>output.txt
. Example:
$ echo 'x = y' | julia &>output.txt
$ cat output.txt
ERROR: UndefVarError: y not defined
Stacktrace:
[1] top-level scope
@ none:1