0

我正在尝试使用prompt-toolkit. 它工作得很好,但是如果很长时间没有输入,我想退出程序。事实证明,这对我来说非常具有挑战性。

以下是 cli 应用程序应该如何工作的一些伪代码:

from prompt_toolkit import PromptSession
import time

def execute(cmd):
    # do long task
    time.sleep(120)

if __name__ == '__main__':
    s = PromptSession()

    while True:
        start_time = time.time()
        cmd = s.prompt('>')
        execute(cmd)

        if time.time() - start_time > 60:
            break

因此,如果用户在最后 60 秒内没有发出命令,程序应该终止。但是如果一个命令的执行时间超过 60 秒,它应该只在命令完成 60 秒后终止(并且没有发出新命令)。

我已经绊倒了第一点。我是否需要并行处理来检查s.prompt运行时的时间?该命令还有一个prompt_async版本。我玩过它,但没有任何成功......

4

1 回答 1

1

因此,我在 asyncio 文档中为我的问题找到了一个非常简单的答案,这正是我搜索的内容:asyncio.wait_for. 解决方案在这里,仅供记录:

from prompt_toolkit import PromptSession
import asyncio

def execute(cmd):
    # do long task
    time.sleep(120)

if __name__ == '__main__':
    s = PromptSession()

    while True:
        try:
            cmd = await asyncio.wait_for(s.prompt_async('>'), timeout=60)
        except asyncio.TimeoutError:
            break
        execute(cmd)
于 2020-05-02T14:35:03.110 回答