How do I check if stdin has some data?

本小妞迷上赌 提交于 2019-11-26 18:48:58

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!