English 中文(简体)
How can a console application (e.g. Java) recognize the source of the standard input stream?
原标题:

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?

问题回答

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)




相关问题
Caching System.Console output

We have some methods that output a lot of coloured text to the Console. It s actually a menu that is built by looping through a collection of data. Because we are writing item by item (and one line ...

console app c++

i m new to console apps and would appreciate some pointers... i have created a new console app and (not finished but it should be working), i selected win32 console app and then selected empty ...

Java prints output twice in a very specific circumstance

System.out.print("My string: "); My string: BUILD SUCCESSFUL (total time: 1 second) System.out.print("My string "); My string BUILD SUCCESSFUL (total time: 1 second) System.out.print("My string: ...

Removing pause after reading using readLine in java

I am reading several lines from the console in a java program using the readLine command from the BufferedReader class. However, the program pauses at the end of the last line and does not proceed ...

热门标签