输入不停止程序 [英] Input without stopping program
本文介绍了输入不停止程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作一个倒计时计时器,打印剩余时间,当您输入内容时,它会打印您输入的内容.我的问题是我不想等待输入,只是继续运行计时器.我的错误代码:
I am trying to make a countdown timer that prints the time remaining, and when you input something, it prints what you inputted. My problem is I don't want to wait for the input, just keep running the timer. My incorrect code:
timer = 100
while True:
print(timer)
timer -= 1
if input('> '):
print('the output of input')
您可以说我想让计时器在后台打印时间.
You could say I want to have the timer printing the time in the background.
推荐答案
如果没有输入,这里的函数将超时:
Here's a function that will timeout if no input is given:
import select
import sys
def timeout_input(timeout, prompt="", timeout_value=None):
sys.stdout.write(prompt)
sys.stdout.flush()
ready, _, _ = select.select([sys.stdin], [], [], timeout)
if ready:
return sys.stdin.readline().rstrip('\n')
else:
sys.stdout.write('\n')
sys.stdout.flush()
return timeout_value
您可以轻松地对其进行修改,以便通过将select.select
上的超时值更改为1
并循环timeout
次来显示剩余时间.
You can easily modify it so it shows the remaining time by changing the timeout value on select.select
to 1
, and looping timeout
times.
这篇关于输入不停止程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文