How do I temporarily capture stdout in Nim?
I would like to have a template with the following signature:
template captureStdout(ident: untyped, body: untyped) = discard
Such that this code (main.nim) runs without error:
var msg = "hello"
echo msg & "1"
var s: string
captureStdout(s):
echo msg & "2"
msg = "ciao"
echo msg & "3"
assert s == "hello2\n"
and the output should be:
hello1
ciao3
current efforts
currently I am able to capture stdout using a temporary file, but I am not able to release back to stdout. I do this with the following:
template captureStdout*(ident: untyped, body: untyped) =
discard reopen(stdout, tmpFile, fmWrite)
body
ident = readFile(tmpFile)
with this main.nim runs without assertion error but output is only
hello1
and in tmpFile I see:
hello2
ciao3