raw_input 和超时

发布于 2024-09-14 06:52:36 字数 138 浏览 4 评论 0原文

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

I want to do a raw_input('Enter something: .'). I want it to sleep for 3 seconds and if there's no input, then cancel the prompt and run the rest of the code. Then the code loops and implements the raw_input again. I also want it to break if the user inputs something like 'q'.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小鸟爱天空丶 2024-09-21 06:52:36

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

编辑[0]:​​显然这在 Windows 上不起作用,因为select() 的底层实现需要套接字,而 sys.stdin 不需要。感谢您的提醒,@Fookatchu。

There's an easy solution that doesn't use threads (at least not explicitly): use select to know when there's something to be read from 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..."

Edit[0]: apparently this won't work on Windows, since the underlying implementation of select() requires a socket, and sys.stdin isn't. Thanks for the heads-up, @Fookatchu.

满身野味 2024-09-21 06:52:36

如果您使用的是 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 

If you're working on Windows you can try the following:

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 
烟花肆意 2024-09-21 06:52:36

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

使用 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()

我知道我添加的内容有点懒,但它有效,而且只是一个示例

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

I have some code which makes a countdown app with a tkinter entry box and button so they can enter something and hit the button, if the timer runs out the tkinter window closes and tells them they ran out of time.
I think most other solutions to this problem don't have a window which pops up so thought id add to the list :)

with raw_input() or input(), it isn't possible as it stops at the input section, until it receives input, then it carries on...

I have taken some code from the following link:
Making a countdown timer with Python and Tkinter?

I used Brian Oakley's answer to this problem and added the entrybox etc.

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

I know what I added was a bit lazy but it works and it is an example only

This code works for Windows with Pyscripter 3.3

Bonjour°[大白 2024-09-21 06:52:36

对于 rbp 的答案:

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

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

For rbp's answer:

To account for input equal to a Carriage Return simply add a nested condition:

if rlist:
    s = sys.stdin.readline()
    print s
    if s == '':
        s = pycreatordefaultvalue
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文