Reputation: 1077
I want my Nim program to write to the console if there is one, and redirect echo
to write to a file if there isn't. Is there an equivalent to the Environment.UserInteractive
property in .NET which I could use to detect if no console is available and redirect stdout in that case?
Upvotes: 1
Views: 597
Reputation: 1370
It's a combination of using isatty()
as suggested by genotrance and the code that you found :)
# stdout_to_file.nim
import terminal, strformat, times
if isatty(stdout): # ./stdout_to_file
echo "This is output to the terminal."
else: # ./stdout_to_file | cat
const
logFileName = "log.txt"
let
# https://github.com/jasonrbriggs/nimwhistle/blob/183c19556d6f11013959d17dfafd43486e1109e5/tests/cgitests.nim#L15
logFile = open(logFileName, fmWrite)
stdout = logFile
echo fmt"This is output to the {logFileName} file."
echo fmt"- Run using nim {NimVersion} on {now()}."
Save above file as stdout_to_file.nim
.
On running:
nim c stdout_to_file.nim && ./stdout_to_file | cat
I get this in the created log.txt
:
This is output to the log.txt file.
- Run using nim 0.19.9 on 2019-01-23T22:42:27-05:00.
Upvotes: 2
Reputation: 49
Edit: @tjohnson this is in response to your comment. I don't have enough points to respond to your comment directly or something? Thanks Stack Overflow...
It's hard to say without seeing more of the code.
What version of Nim are you using?
I suspect stdout has been shadowed by a read only symbol.
Are you calling this code inside of a proc and passing stdout as an argument?
like this:
proc foo(stdout: File)
If so, you will need to change it to a var parameter to make the argument writable:
proc test(stdout: var File)
Or use stdout as a global variable instead.
Upvotes: 1
Reputation: 413
You should be able to use isatty().
Here's an example in Nimble.
Upvotes: 1