2

For example if you took over 10 seconds to answer an input the program would print text or execute some line of code. You could still answer, just text would be printing while you haven't answered, or something similar to that.

ti7
  • 16,375
  • 6
  • 40
  • 68
  • 1
    broadly, yes, but you probably need another [thread](https://docs.python.org/3/library/threading.html) or [coroutine](https://stackoverflow.com/questions/29081929/prompt-for-user-input-using-python-asyncio-create-server-instance) – ti7 Feb 28 '22 at 21:31
  • Welcome to StackOverflow. This is an **interactive** community. Interact with the community so they can tell if your question has been answered. If an answer meets your needs accept the answer. If your question has not been answered add comments. Possibly clarify your question. The [tour](https://stackoverflow.com/tour) and [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) provides information to help you succeed. **The question does not include code. That increases the chance it will be downvoted or closed with no answer..** – Carl_M Feb 28 '22 at 21:45
  • @ti7 can you please make an example in this case? – Shayan Feb 28 '22 at 21:45
  • If you were hoping to be told that the built-in function `input()` has an undocumented timeout parameter, I have to disappoint you. It doesn’t. What you want can be done, but it requires fairly sophisticated programming that may be overambitious for your present level. The time you would need to spend learning how to do it would be better devoted to learning a GUI framework like `Tkinter` or `wx` that supports keyboard event handling (which is what you are reaching for) out of the box. – BoarGules Feb 28 '22 at 22:02
  • Which operating systems? In linux and mac, `signal.alarm` can interrupt `input`, as long as `input` is called on the main thread. Windows is a bit more difficult. – tdelaney Feb 28 '22 at 22:09

1 Answers1

3

You can achieve something like this with threading. Here's a very simple example:

from threading import Thread
from time import sleep

def ask():
  text = input("Type something ")
  print(text)

def timeout():
  sleep(5)
  print("timed out!")

for i in (Thread(target=ask), Thread(target=timeout)):
    # Start 'ask' and 'timeout' as threads
    i.start()

Both functions will run in parallel, and you will see the timeout message printed after 5 seconds, separate to the input.

If you want to be more complex you can keep references to running threads and allow either thread to stop the other (e.g. cancelling the timeout if the user inputs something).

match
  • 10,388
  • 3
  • 23
  • 41