raw_input 和超时[重复]
- 2025-02-18 09:23:00
- admin 原创
- 36
问题描述:
我想做一个raw_input('Enter something: .')
。我希望它休眠 3 秒,如果没有输入,则取消提示并运行其余代码。然后代码循环并raw_input
再次实现。我还希望它在用户输入类似“q”的内容时中断。
解决方案 1:
有一个简单的解决方案,不使用线程(至少不是明确使用的):使用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 的提醒。
解决方案 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
解决方案 3:
我有一些代码可以制作一个带有 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
解决方案 4:
对于rbp的回答:
为了解释等于回车符的输入,只需添加一个嵌套条件:
if rlist:
s = sys.stdin.readline()
print s
if s == '':
s = pycreatordefaultvalue
相关推荐
热门文章
项目管理软件有哪些?
- 2025年20款好用的项目管理软件推荐,项目管理提效的20个工具和技巧
- 2024年开源项目管理软件有哪些?推荐5款好用的项目管理工具
- 2024年常用的项目管理软件有哪些?推荐这10款国内外好用的项目管理工具
- 项目管理软件有哪些?推荐7款超好用的项目管理工具
- 项目管理软件有哪些最好用?推荐6款好用的项目管理工具
- 项目管理软件哪个最好用?盘点推荐5款好用的项目管理工具
- 项目管理软件排行榜:2024年项目经理必备5款开源项目管理软件汇总
- 项目管理必备:盘点2024年13款好用的项目管理软件
- 项目管理软件有哪些,盘点推荐国内外超好用的7款项目管理工具
- 2024项目管理软件排行榜(10类常用的项目管理工具全推荐)
热门标签
云禅道AD