简体   繁体   English

Python:如何判断输入文件是否有输入待处理而无需等待

[英]Python: how to tell if input file has input pending without waiting

Normally, you process a file line by line in Python using a loop like: 通常,您可以使用以下循环在Python中逐行处理文件:

import sys
for s in sys.stdin:
    # do something with the line in s

or 要么

import sys
while True:
    line = sys,stdin.readline()
    if len(line) == 0: break
    # process input line

Of course, you can also use raw_input() in soemthing like this: 当然,您也可以像这样使用raw_input():

try:
    while True:
        s = raw_input()
        # process input line
except EOFError:
    # there's EOF.

Of course in all these cases, if there's no input ready to be read, the underlying read() operation suspends waiting for I/O. 当然,在所有这些情况下,如果没有可供读取的输入,则底层的read()操作将挂起以等待I / O。

What I want to do is see if there is input pending without suspending, so I can read until input is exhausted and then go do something else. 我想做的是查看是否有待处理的输入暂停,因此我可以阅读直到输入用尽,然后再执行其他操作。 That is, I'd like to be able to do something like 也就是说,我希望能够做类似的事情

while "there is input pending":
    #get the input

but when no more input is pending, break the loop. 但是当没有其他输入待处理时,请中断循环。

If you are using some variant of Unix, and your standard input is a pipe and not a file, you can use the select module to check to see whether there is waiting input. 如果使用的是Unix的某些变体,并且标准输入是管道而不是文件,则可以使用select模块检查是否有等待的输入。 At a minimum, the code might look like: 至少,代码可能看起来像:

import select

rlist, wlist, elist = select.select([sys.stdin], [], [])
if rlist:
    s = raw_input()
else:
    pass # no input ready right now

Okay, here's something that works well on UNIX: 好的, 在UNIX上可以很好地工作:

import sys
import select
import tty
import termios


def isData():
    return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

old_settings = termios.tcgetattr(sys.stdin)
try:
    tty.setcbreak(sys.stdin.fileno())

    i = 0
    while 1:
        print i
        i += 1

        if isData():
            c = sys.stdin.read(1)
            if c == '\x1b':         # x1b is ESC
                break

finally:
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

I'll modify/extend this answer when I have a chance to make a somewhat better test program. 有机会制定更好的测试程序时,我将修改/扩展此答案。 I'm (so far) unclear on how well tty and termios work on Windows. 我(到目前为止)还不清楚ttytermios在Windows上的运行情况。

Update : Grmph. 更新 :Grmph。 This depends on select . 这取决于select There are reasons I don't like Windows. 有一些原因我不喜欢Windows。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM