How do I check if stdin has some data? How do I check if stdin has some data? python python

How do I check if stdin has some data?


On Unix systems you can do the following:

import sysimport selectif select.select([sys.stdin,],[],[],0.0)[0]:    print "Have data!"else:    print "No data"

On Windows the select module may only be used with sockets though so you'd need to use an alternative mechanism.


I've been using

if not sys.stdin.isatty()

Here's an example:

import sysdef main():    if not sys.stdin.isatty():        print "not sys.stdin.isatty"    else:        print "is  sys.stdin.isatty"

Running

$ echo "asdf" | stdin.pynot sys.stdin.isatty

sys.stdin.isatty() returns false if stdin is not connected to an interactive input device (e.g. a tty).

isatty(...)    isatty() -> true or false. True if the file is connected to a tty device.


Depending on the goal here:

import fileinputfor line in fileinput.input():    do_something(line)

can also be useful.