Testing Whether a Program Is Running Interactively

Table of contents:

Problem

You want to see whether theres 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 theres a terminal hooked up to your programs 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.



Strings

Numbers

Date and Time

Arrays

Hashes

Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming

XML and HTML

Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration



Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net