Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 473
mlzboy Avatar asked Sep 21 '10 17:09

mlzboy


People also ask

What is the buffer of stdin?

Default Buffer sizes: if stdin/stdout are connected to a terminal then default size = 1024; else size = 4096.


1 Answers

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.

like image 184
Rakis Avatar answered Sep 19 '22 01:09

Rakis