UPDATE: Perhaps the preferred means for this is the STDIN.isatty method, which returns true if running in a console window and false otherwise...
if STDIN.isatty
# do some command-line stuff
else
# do some GUI stuff
end
Thanks to Brent and Dan for their comments.
Alternatively, Nobu Nakada mentioned in a recent Ruby Forum post that you cannot open the CONIN$ (console input) device file unless you are running in a console window. So the following method (adapted from Nobu) would return true if running in a console window and false otherwise...
def in_console?
begin
open("CONIN$") {}
console = true
rescue SystemCallError
console = false
end
return console
end
Usage example:
if in_console?
# do some command-line stuff
else
# do some GUI stuff
end
There you have it. Got a question or suggestion? Post a comment or send me email.
Thanks for stopping by!
I usually just test...
ReplyDeleteSTDIN.isatty
(if someone has a reason that that won't work, I'd appreciate knowing)
Cheers.
--Brent
I've no idea where Nobu was going with that. The isatty() function is supported in MSVCRT, so Brent's suggestion of STDIN.isatty should be preferred.
ReplyDeleteIt's what I've always used.
--Dan
Thanks, Brent and Dan!
ReplyDeleteI've updated the post to suggest using the STDIN.isatty method, which works for me. I've also added a link to the Ruby Forum message thread that I referenced.
David