'How to get what is on the terminal in Nim lang

How can I store what is on the terminal (console) as a string in Nim?

For example, let's say my console is showing this:

   Success: Execution finished
   Success: All tests passed
(base) piero@Somebodys-MacBook-Pro Tests % 

I want to store that as a string to a variable.
How can I achieve that?

In bash, it may be achieved by something like this:

ls -ltr > ./output.txt


Solution 1:[1]

You can either use std/osproc's execCmdEx or startProcess the former runs the the command and returns the (stdout, exitcode) the latter allows you to interact with the process while it's running:

import std/[streams, osproc]
# For the startProcess variant
let myProc = startProcess("ls", args = ["-ltr"], options = {poUsePath})
discard myProc.waitForExit() # Force the program to block until done, not needed if have other computation
let myOutput = myProc.outputstream.readAll
myProc.close() # Free Resources

# For execShellEx variant
let (output, _) = execCmdEx("ls -ltr")
assert output.len == myOutput.len # Just for showcase

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jason