【问题标题】:raw_input and timeout [duplicate]raw_input 和超时 [重复]
【发布时间】:2011-03-29 03:20:59
【问题描述】:

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

【问题讨论】:

标签: python loops raw-input


【解决方案1】:

有一个不使用线程的简单解决方案(至少不明确地):使用select 知道何时需要从标准输入读取内容:

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

Edit[0]:显然这是won't work on Windows,因为 select() 的底层实现需要一个套接字,而 sys.stdin 不需要。感谢@Fookatchu 的提醒。

【讨论】:

  • 无法使用此功能,因为我公司的计算机使用的是 2.3.3。谢谢。
  • select 模块在 python 2.3 中。
  • 我收到此错误:回溯(最近一次调用最后一次):文件“Z:\test.py”,第 6 行,在 rlist, _, _ = select([sys .stdin], [], [], timeout) TypeError: argument must be an int, or have a fileno() method.
  • 不错。顺便说一句,我必须在打印提示后 sys.stdout.flush() 才能看到它
【解决方案2】:

如果您在 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 

【讨论】:

  • 这在命令行中可以正常工作,但在 Eclipse 中运行时将无法正常工作,我不确定如何让 msvcrt 从 Eclipse 中读取键盘。
  • 我从未使用过 Eclipse for Python,但我猜这与 sublimtext 相同,内置控制台不是一个正确的实现,只是一个输出。我相信您可以将 Eclipse 配置为在这种情况下使用真正的终端或 cmd,这样您就可以对其进行输入。
  • @Paul - 这对我在 Windows 上不起作用。除了将 Print 更改为 py3 语法并添加 stdout.flush() 之外,我正在逐字运行您的代码。 Windows7、python3.6
  • 仅供参考——您不应该使用 chr 作为变量名来覆盖内置函数
【解决方案3】:

我有一些代码可以制作一个带有 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

【讨论】:

    【解决方案4】:

    对于 rbp 的回答:

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

    if rlist:
        s = sys.stdin.readline()
        print s
        if s == '':
            s = pycreatordefaultvalue
    

    【讨论】:

      猜你喜欢
      • 2011-03-29
      • 1970-01-01
      • 2011-04-17
      • 2015-01-11
      • 1970-01-01
      • 2014-03-10
      • 2016-05-12
      • 2016-07-30
      • 1970-01-01
      相关资源
      最近更新 更多