I need to collect everything from terminal and write it to a txt file. Julia language enter image description here
Asked
Active
Viewed 550 times
2 Answers
3
In Julia 1.7 you can just do:
redirect_stdio(stdout="stdout.txt", stderr="stderr.txt") do
println("hello")
println(stderr, "hello error")
end
In older Julia versions you need to implement this functionality yourself (the code taken from https://discourse.julialang.org/t/redirect-stdout-and-stderr/13424/3):
function redirect_to_files(dofunc, outfile, errfile)
open(outfile, "w") do out
open(errfile, "w") do err
redirect_stdout(out) do
redirect_stderr(err) do
dofunc()
end
end
end
end
end
Which now can be used as:
redirect_to_files("stdout.txt","stderr.txt") do
println("hello")
println(stderr, "hello error")
end
If you do not want to use the do
syntax you can also open and close the streams yourself.

Przemyslaw Szufel
- 40,002
- 3
- 32
- 62
-
-
In my examples `stdout.txt` and `stderr.txt` are just text files. If you want to simultaneously do both things you would perhaps need to use TranscodingStreams.jl, and create a stream transcoder that does no encoding but sends the bytes to the console. – Przemyslaw Szufel Sep 06 '21 at 13:53
0
The println
and @show
messages go to stdout
which is the Julia REPL console by default. The @info, @debug, @warn, @error
macros are logging utilities and they are set to use a ConsoleLogger by default, again using the Julia REPL.
If we want both the print-like commands and logging commands to go to a text file this is what we have to do:
redirect_stdio(stdout="log_file.txt") do
logger = ConsoleLogger(stdout) # redirect @info and other logging macros to the new stdout
with_logger(logger) do
@info "start logging"
println("results are good")
end
end

Marius D
- 43
- 5