Categories
Python Answers

How to set time limit on raw_input with Python?

Spread the love

Sometimes, we want to set time limit on raw_input with Python.

In this article, we’ll look at how to set time limit on raw_input with Python.

How to set time limit on raw_input with Python?

To set time limit on raw_input with Python, we can use the threading module.

For instance, we write

import thread
import threading

def raw_input_with_timeout(prompt, timeout=30.0):
    print(prompt, end=' ')    
    timer = threading.Timer(timeout, thread.interrupt_main)
    astring = None
    try:
        timer.start()
        astring = input(prompt)
    except KeyboardInterrupt:
        pass
    timer.cancel()
    return astring

to create the raw_input_with_timeout function.

In it, we call threading.Timer to create a timer.

And then we call timer.start to start the timer.

Then we call input to prompt for the input.

Next, we cal timer.cancel to cancel the timer once input is read.

And then we return the string once a value is entered or the timer timed out.

This works on Windows and Unix based OS’s.

Conclusion

To set time limit on raw_input with Python, we can use the threading module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *