Tuesday, June 3, 2008

Running In A Console Window?

Someone recently asked me how to determine if your code is running in a console window or not. Perhaps you have a program that provides both GUI and command line interfaces and you need to know which interface is being used. You may wish to output error messages to the console, if it exists, but to a file if the console doesn't exist.

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!

3 comments:

sbfaulkner said...

I usually just test...

STDIN.isatty

(if someone has a reason that that won't work, I'd appreciate knowing)

Cheers.

--Brent

Daniel Berger said...

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.

It's what I've always used.

--Dan

David Mullet said...

Thanks, Brent and Dan!

I'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