How do I check if stdin has some data?

孤街浪徒 提交于 2019-11-26 06:35:30

问题


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?


回答1:


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.




回答2:


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.



回答3:


Depending on the goal here:

import fileinput
for line in fileinput.input():
    do_something(line)

can also be useful.




回答4:


(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.




回答5:


Using built in modules this can be achieved with following code as Greg gave already the idea:

import fileinput
isStdin = True
for line in fileinput.input:
    # check if it is not stdin
    if not fileinput.isstdin():
        isStdin = False
        break
    # continue to read stdin
    print(line)
fileinput.close()




来源:https://stackoverflow.com/questions/3762881/how-do-i-check-if-stdin-has-some-data

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