pythonprompt-toolkit

prompt-toolkit terminate program when idle


I am trying to write a simple command line application with 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:

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. 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).

I already stumble over the first bit. Do I need parallel processing to check the time while s.prompt is running? There is also a prompt_async version of the command. I played around with it, but didn't have any success...


Solution

  • So, I found a very simple answer for my question in the asyncio documentation, which does exactly what I searched for: 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)