In Python, how do you check if sys.stdin
has data or not?
I found that os.isatty(0)
can not only check if stdin is connected to a TTY device, but also if there is data available.
But if someone uses code such as
sys.stdin = cStringIO.StringIO("ddd")
and after that uses os.isatty(0)
, it still returns True. What do I need to do to check if stdin has data?
On Unix systems you can do the following:
import sys
import select
if 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.