raw_input 和超时

38 投票
4 回答
42308 浏览
提问于 2025-04-16 02:43

我想要使用 raw_input('请输入内容: .') 这个功能。我希望它能等待3秒,如果在这段时间内没有输入内容,就取消这个提示,然后继续执行后面的代码。接着,代码会循环,再次执行 raw_input。另外,如果用户输入了像 'q' 这样的内容,我也希望能结束这个过程。

4 个回答

2

我有一些代码,可以做一个倒计时应用,里面有一个tkinter的输入框和按钮,用户可以在输入框里输入内容,然后点击按钮。如果倒计时结束,tkinter窗口就会关闭,并告诉用户时间到了。

我觉得其他大多数解决方案都没有弹出窗口,所以我想把这个方法也分享出来 :)

使用raw_input()或input()是不行的,因为它会在输入的地方停下来,直到收到输入后才会继续执行...

我从以下链接获取了一些代码:用Python和Tkinter制作倒计时器?

我使用了Brian Oakley对这个问题的回答,并添加了输入框等功能。

import tkinter as tk

class ExampleApp(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        def well():
            whatis = entrybox.get()
            if whatis == "": # Here you can check for what the input should be, e.g. letters only etc.
                print ("You didn't enter anything...")
            else:
                print ("AWESOME WORK DUDE")
            app.destroy()
        global label2
        label2 = tk.Button(text = "quick, enter something and click here (the countdown timer is below)", command = well)
        label2.pack()
        entrybox = tk.Entry()
        entrybox.pack()
        self.label = tk.Label(self, text="", width=10)
        self.label.pack()
        self.remaining = 0
        self.countdown(10)

    def countdown(self, remaining = None):
        if remaining is not None:
            self.remaining = remaining

        if self.remaining <= 0:
            app.destroy()
            print ("OUT OF TIME")


        else:
            self.label.configure(text="%d" % self.remaining)
            self.remaining = self.remaining - 1
            self.after(1000, self.countdown)

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()

我知道我添加的东西有点懒,但它能工作,而且只是一个示例。

这段代码适用于Windows系统,使用Pyscripter 3.3。

16

如果你在使用Windows系统,可以试试下面的方法:

import sys, time, msvcrt

def readInput( caption, default, timeout = 5):
    start_time = time.time()
    sys.stdout.write('%s(%s):'%(caption, default));
    input = ''
    while True:
        if msvcrt.kbhit():
            chr = msvcrt.getche()
            if ord(chr) == 13: # enter_key
                break
            elif ord(chr) >= 32: #space_char
                input += chr
        if len(input) == 0 and (time.time() - start_time) > timeout:
            break

    print ''  # needed to move to next line
    if len(input) > 0:
        return input
    else:
        return default

# and some examples of usage
ans = readInput('Please type a name', 'john') 
print 'The name is %s' % ans
ans = readInput('Please enter a number', 10 ) 
print 'The number is %s' % ans 
62

这里有个简单的解决办法,不需要使用线程(至少不是显式地):可以用 select 来判断标准输入(stdin)是否有东西可以读取:

import sys
from select import select

timeout = 10
print "Enter something:",
rlist, _, _ = select([sys.stdin], [], [], timeout)
if rlist:
    s = sys.stdin.readline()
    print s
else:
    print "No input. Moving on..."

编辑[0]:显然这个方法在Windows上 不太好用,因为select()的底层实现需要一个套接字,而sys.stdin并不是。感谢@Fookatchu的提醒。

撰写回答