Simple `redirect_stdout` example

I am struggling to get any example with redirect_stdout to work. There isn’t any documentation on it. E.g.

julia> f, io = mktemp();

julia> fout = open(f, "w+");

julia> redirect_stdout(fout) do
       println("Hello!")
       end;

julia> close(fout)

julia> read(fout)
UInt8[]

julia> read(fout, String)
""

Any ideas? most of the examples I find on the discourse are too old, and no longer work

Don’t read from a closed file handle or the end of a file. After the redirect block, try seek(fout, 0); read(fout, String).

2 Likes

Thanks! This works with Julia I/O, but not when calling C. In fact something strange happens where it dumps the C stdout upon exiting Julia:

% julia
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.10.10 (2025-06-27)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia> f, ios = mktemp();

julia> fout = open(f, "w+");

julia> redirect_stdout(fout) do
         @ccall printf("hello!"::Cstring)::Cint;
       end
6

julia> seek(fout, 0); read(fout, String)
""

julia> exit()
hello!%   

“Something strange” is probably buffering of the I/O on the C side? Try calling Libc.flush_cstdio() after the printf.

2 Likes

That worked! Thank you!

Might have to flush on the Julia side too, I’ve been taking the apparent timeliness of REPL printing for granted but writes can be delayed by buffering otherwise.