views:

56

answers:

1

If I run 'python' on the linux command line, and I don't provide any command line arguments, the program displays a welcome message and waits for user input. I would assume that under the hood, the program sends the message to the 'standard output' stream and performs a blocking read on the 'standard input' stream.

If, however, I invoke python indirectly by piping the output from another process (e.g. echo "hello" | python), python does NOT output the message. Somehow, it can tell the difference between the original scenario (a) where the 'standard input' stream is being populated by some other process and (b) where the 'standard input' stream is populated from the keyboard.

How is this accomplished? I had always thought that this information is not available to an application. How would a Java application be able to achieve this differentiation?

+1  A: 

Python:

import os
import sys

if os.isatty(sys.stdin.fileno()):
    print "is a tty"
else:
    print "not a tty"

I'm not aware of a Java equivalent using the default libraries; Jython appears to use native code (jna-posix).

Update - here's two possibilities:

  • System.console() returns a console object if there is one; null otherwise (see here and here)
  • System.out.available() returns 0 if there's no input immediately available, which tends to mean stdin is a terminal (but not always - this is a less accurate test)
SimonJ