1

I need to collect everything from terminal and write it to a txt file. Julia language enter image description here

OskanZ
  • 57
  • 4
  • 1
    your imagine is a black square it seems – jling Sep 04 '21 at 19:34
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 11 '21 at 06:01

2 Answers2

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
  • How can I collect info to a txt file and print to terminal? – OskanZ Sep 06 '21 at 08:08
  • 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