[英]prompt-toolkit terminate program when idle
I am trying to write a simple command line application with prompt-toolkit
.我正在尝试使用
prompt-toolkit
编写一个简单的命令行应用程序。 It works quite well, however I want to quit the program if there was no input for a long time.它工作得很好,但是如果很长时间没有输入,我想退出程序。 This turned out to be very challenging for me.
事实证明,这对我来说非常具有挑战性。
Here is some pseudo code for what the cli app should kind of work like:以下是 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
So the program should terminate if the user didn't issue a command in the last 60 seconds.因此,如果用户在最后 60 秒内没有发出命令,程序应该终止。 But if a command is executed which takes longer than 60 seconds, it should only be terminated 60 seconds after the command finished (and no new command was issued).
但是如果一个命令的执行时间超过 60 秒,它应该只在命令完成 60 秒后终止(并且没有发出新命令)。
I already stumble over the first bit.我已经绊倒了第一点。 Do I need parallel processing to check the time while
s.prompt
is running?我是否需要并行处理来检查
s.prompt
运行时的时间? There is also a prompt_async
version of the command.该命令还有一个
prompt_async
版本。 I played around with it, but didn't have any success...我玩过它,但没有任何成功......
So, I found a very simple answer for my question in the asyncio documentation, which does exactly what I searched for: asyncio.wait_for
.因此,我在 asyncio 文档中为我的问题找到了一个非常简单的答案,它完全符合我的搜索要求:
asyncio.wait_for
。 The solution is here, just for the record:解决方案在这里,仅供记录:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.