Here is a way to do this using pipes and threads (which, unlike the suggested duplicate, is not limited to a predefined buffer size or risks a buffer overflow vulnerabillity):
- Create a pipe using
std.process.pipe
- Set
stdout
to the pipe's write end (back it up first) - Spawn a thread which would read from the pipe's read end and append output to a string, until the pipe is closed
- Execute the task at hand
- Close the write end of the pipe
- Restore the old value of
stdout
- Wait for the thread to finish execution
- Use the buffer created by the thread
I have some similar code, albeit in the other direction (asynchronous writing as opposed to reading), here and here.