How do I check if stdin has some data?

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

    print "Have data!"
    print "No data"

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

Leave a Reply

Your email address will not be published. Required fields are marked *