3

This is my attempt:

from inputimeout import inputimeout, TimeoutOccurred
import time
import sys
import os


def get_choice(maxtimeout=9):
    try:
        for remaining in range(maxtimeout, 0, -1):
            sys.stdout.write("\r")
            sys.stdout.write(
                "Want to continue to next item(Y/N)? Defaults to Y in {:2d} seconds...".format(
                    remaining + 1
                )
            )
            sys.stdout.flush()
            time.sleep(1)
        c = inputimeout(prompt="", timeout=1)
    except TimeoutOccurred:
        c = "Y"
    return c

The issues with my approach are:

  1. The inputed key is not visible until the timeout completes.
  2. The user has to press enter after his choice.
  3. The user has to wait till timeout completes irrespective of when he entered the value.
1
  • 1
    You can use the signal module to set a timer to go off if the user hasn't provided input within the given amount of time. I can provide an example later if you're unable to get it working.
    – sj95126
    Commented Sep 22, 2021 at 1:43

1 Answer 1

1

There are two problems to solve here to meet your preferred requirements.

First, here's a simple example of how you can use a signal timer to give the user some amount of time to input an answer:

import signal

def input_timeout(*ignore):
    raise TimeoutError

signal.signal(signal.SIGALRM, input_timeout)
signal.setitimer(signal.ITIMER_REAL, 10)

try:
    inp = input("enter something: ")
    signal.setitimer(signal.ITIMER_REAL, 0)
except TimeoutError:
    print("you took too long!")

What this does is set a timer to go off after 10 seconds (you can use fractional time if you want, say, 2.5 seconds). If the user hasn't input anything before the timer goes off, it raises the TimeoutError exception, breaking the input prompt. If the user does enter something, it disables the timer by setting it to zero. If the timer does fire and calls input_timeout(), it passes two arguments (the signal number and the interrupted stack frame) but you can usually ignore them, so I've set those arguments as *ignore.

Here's a question that covers this approach in more detail: Python timeout decorator. The reason I didn't just point you to that is so that you could see the bare essence of the process and decide for yourself how to use it. Plus, well, when I pasted the code and tried to use it, it didn't work. You can decide how to proceed as meets your needs.

The second issue is you mention the problem with your approach is the user having to press enter. Here's a question that covers that topic: raw_input in python without pressing enter. In short, there's not a simple built-in solution for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.