Python 原始输入和超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3471461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
raw_input and timeout
提问by ykmizu
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_inputagain. I also want it to break if the user inputs something like 'q'.
我想做一个raw_input('Enter something: .'). 我希望它休眠 3 秒钟,如果没有输入,则取消提示并运行其余代码。然后代码循环并raw_input再次实现。如果用户输入诸如“q”之类的内容,我也希望它中断。
回答by rbp
There's an easy solution that doesn't use threads (at least not explicitly): use selectto know when there's something to be read from stdin:
有一个不使用线程的简单解决方案(至少不是明确的):使用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..."
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.
Edit[0]: 显然这在 Windows 上不起作用,因为 select() 的底层实现需要一个套接字,而 sys.stdin 不是。感谢您的提醒,@Fookatchu。
回答by Paul
If you're working on Windows you can try the following:
如果您使用的是 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
回答by maphilli14
For rbp's answer:
对于 rbp 的回答:
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
回答by W1ll1amvl
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 :)
我有一些代码可以制作一个带有 tkinter 输入框和按钮的倒计时应用程序,这样他们就可以输入一些东西并点击按钮,如果计时器用完,tkinter 窗口就会关闭并告诉他们时间用完了。我认为这个问题的大多数其他解决方案都没有弹出窗口,所以认为 id 添加到列表中:)
with raw_input() or input(), it isn't possible as it stops at the input section, until it receives input, then it carries on...
使用 raw_input() 或 input(),这是不可能的,因为它停在输入部分,直到它接收到输入,然后才继续......
I have taken some code from the following link: Making a countdown timer with Python and Tkinter?
我从以下链接中获取了一些代码: 使用 Python 和 Tkinter 制作倒数计时器?
I used Brian Oakley's answer to this problem and added the entrybox etc.
我使用了 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()
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
此代码适用于带有 Pyscripter 3.3 的 Windows

