【问题标题】:Input timeout with countdown timer in python在python中使用倒数计时器输入超时
【发布时间】:2021-09-09 16:33:49
【问题描述】:

任何人都知道如何做某事,就像这段代码一样

import subprocess  
subprocess.call('timeout /T 30')

主要思想是等待用户输入一段特定的时间,并向用户显示距离结束还有多少秒。 上面代码的问题是无法更改显示文本 找不到适用于 windows 的解决方案...

【问题讨论】:

标签: python input subprocess timeout


【解决方案1】:

这是我的看法:

import asyncio

async def setInterval(callback, countdown):
    async def job():
        if countdown <= 0:
            print('Countdown finished')
            return

        await asyncio.sleep(1)
        callback(countdown)
        await setInterval(callback, countdown-1)

    await asyncio.ensure_future(job())  

def myCallback(timeLeft):
    print(f'Time left: {timeLeft}')

async def otherTask():
    while True:
        print('some other code running')
        await asyncio.sleep(2)

async def main():
    await asyncio.gather(
        setInterval(myCallback, 10),
        otherTask()
    )

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(main())

上面的代码让您可以每秒触发函数myCallback,您可以使用它来向用户显示剩余时间,而不会阻塞您可能希望在倒计时时运行的其他代码。

示例输出如下:

some other code running
Time left: 10
some other code running
Time left: 9
Time left: 8
some other code running
Time left: 7
Time left: 6
some other code running
Time left: 5
Time left: 4
some other code running
Time left: 3
Time left: 2
some other code running
Time left: 1
Countdown finished
some other code running
some other code running
some other code running

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多