简体   繁体   中英

Is there a way to make something happen if somebody takes too long to answer an input on Python?

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.

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 (eg cancelling the timeout if the user inputs something).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM