我想要执行一个
raw_input('输入一些内容: .')
。我希望它暂停3秒钟,如果没有输入,则取消提示并运行其余的代码。然后代码循环并再次执行raw_input
。如果用户输入像'q'这样的东西,我也希望它中断。raw_input('输入一些内容: .')
。我希望它暂停3秒钟,如果没有输入,则取消提示并运行其余的代码。然后代码循环并再次执行raw_input
。如果用户输入像'q'这样的东西,我也希望它中断。有一个简单的解决方案,不需要使用线程(至少不需要显式地使用线程):使用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提供信息。
select
模块在 Python 2.3 中。 - habnabitsys.stdout.flush()
才能看到它。 - mykhal如果你正在使用 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
chr
作为变量名来覆盖内置函数。 - kevinsa5getwche
可能对某些人来说是必需的 - v010dyaimport 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
对于rbp的回答:
为了处理等于回车符的输入,只需添加一个嵌套条件:
if rlist:
s = sys.stdin.readline()
print s
if s == '':
s = pycreatordefaultvalue