Testing Whether a Program Is Running Interactively






Testing Whether a Program Is Running Interactively

Problem

You want to see whether there's another person on the other end of your program, or whether the program has been hooked up to a file or the output of another program.

Solution

STDIN.tty? returns true if there's a terminal hooked up to your program's original standard input. Since only humans use terminals, this will suffice. This code works on Unix and Windows:

	#!/usr/bin/ruby -w
	# interactive_or_not.rb
	if STDIN.tty?
	  puts "Let me be the first to welcome my human overlords."
	else
	  puts "How goes the revolution, brother software?"
	end

Running this program in different ways gives different results:

	$ ./interactive_or_not.rb
	Let me be the first to welcome my human overlords.

	$ echo "Some data" | interactive_or_not.rb
	How goes the revolution, brother software?

	$ ./interactive_or_not.rb < input_file
	How goes the revolution, brother software?

Discussion

An interactive application can be more user friendly than one that runs solely off its command-line arguments and input streams. By checking STDIN.tty? you can make your program have an interactive and a noninteractive mode. The noninteractive mode can be chained together with other programs or used in shell scripts.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows