Python中在同一行使用'read_input'的倒计时循环
我想做一个倒计时循环,使用普通的 raw_input
,但是 raw_input
的内容不变,只有数字会变化。
也就是说,像这样 你想再试一次吗? [15-1] 会在一行上输出,只有数字在变化。
这是我目前的代码,但它不工作。那么我该怎么做呢?
while True:
for i in range(15,-1,-1):
con1=raw_input("\n Do you want to try again? " + str(i,))
if i == 0:
print "\n Thanks for playing!"
exit(0)
elif con1 == "no":
print "\n Thanks for playing!"
time.sleep(3)
exit(0)
elif con1 == "yes":
break
1 个回答
3
Linux的答案 -- 在Windows上无法使用
Python 3
import select
import sys
def has_input(timeout=0.0):
return select.select([sys.stdin], [], [], timeout)[0]
def getans(timeout=15):
i = timeout
max_num_length = len(str(timeout))
while i:
print("\rDo you want to try again? {:{}} ".format(i, max_num_length),
end="", flush=True)
i -= 1
if has_input(1):
return input()
print()
return None
print(getans())
Python 2
import select
import sys
def has_input(timeout=0.0):
return select.select([sys.stdin], [], [], timeout)[0]
def getans(timeout=15):
i = timeout
max_num_length = len(str(timeout))
while i:
sys.stdout.write("\rDo you want to try again? {:{}} ".format(i, max_num_length))
sys.stdout.flush()
i -= 1
if has_input(1):
return raw_input()
print
return None
print getans(5)
getans
在超时的情况下会返回 None
,否则会返回响应结果。理论上,如果能实现一个适用于Windows的 has_input
版本,这个方法在Windows上也许可以用,但我还没有测试过。