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.
I've been using
if not sys.stdin.isatty()
Here's an example:
4 import sys
5
6 def main():
7 if not sys.stdin.isatty():
8 print "not sys.stdin.isatty"
9 else:
10 print "is sys.stdin.isatty"
>echo "asdf" | stdin.py
not sys.stdin.isatty
sys.stdin.isatty() returns false if there's something in stdin.
isatty(...)
isatty() -> true or false. True if the file is connected to a tty device.
Depending on the goal here:
import fileinput
for line in fileinput.input():
do_something(line)
can also be useful.
(edit: This answers a related question that has since been merged here.)
As mentioned by others, there's no foolproof way to know if data will become available from stdin, because UNIX doesn't allow it (and more generally because it can't guess the future behavior of whatever program stdin connects to).
Always wait for stdin, even if there may be nothing (that's what grep etc. do), or ask the user for a - argument.
来源:https://stackoverflow.com/questions/3762881/how-do-i-check-if-stdin-has-some-data