37

我想做一个raw_input('Enter something: .'). 我希望它休眠 3 秒,如果没有输入,则取消提示并运行其余代码。然后代码循环并raw_input再次实现。如果用户输入“q”之类的内容,我也希望它中断。

4

4 回答 4

59

有一个不使用线程的简单解决方案(至少不明确):使用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 的提醒。

于 2010-08-12T20:41:52.147 回答
15

如果您在 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 
于 2010-10-12T03:50:13.773 回答
2

我有一些代码可以制作一个带有 tkinter 输入框和按钮的倒计时应用程序,这样他们就可以输入一些东西并点击按钮,如果计时器用完,tkinter 窗口就会关闭并告诉他们时间用完了。我认为这个问题的大多数其他解决方案都没有弹出窗口,所以认为 id 添加到列表中:)

使用 raw_input() 或 input(),它是不可能的,因为它在输入部分停止,直到它接收到输入,然后它继续......

我从以下链接中获取了一些代码: Making a countdown timer with Python and 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()

我知道我添加的内容有点懒惰,但它确实有效,这只是一个示例

此代码适用于带有 Pyscripter 3.3 的 Windows

于 2014-06-08T03:50:03.507 回答
1

对于 rbp 的回答:

要考虑等于回车的输入,只需添加一个嵌套条件:

if rlist:
    s = sys.stdin.readline()
    print s
    if s == '':
        s = pycreatordefaultvalue
于 2012-10-01T04:43:46.970 回答