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?
Default Buffer sizes: if stdin/stdout are connected to a terminal then default size = 1024; else size = 4096.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With