Open In App

How to set an input time limit in Python?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will explain how to set an input time limit in Python. It is one of the easiest programming languages which is not only dynamically typed but also garbage collected. Here we will look at different methods to set an input time limit. Below are the methods we will use in this article.

Methods to Set an Input Time Limit in Python

  • Using the inputimeout module
  • Using the select module
  • Using the signal module
  • Using the threading module

Set an Input Time Limit using the inputimeout module

Inputimeout: The module in Python helps users to take input on multiple platforms but also handles the timed input. This module can be installed in Python through the following command:

pip install inputimeout

Example:

First of all, import the libraries. Now, create a try-except statement, the try block to execute lines of code and except to handle errors in the program. Here, we used the inputimeout() function, which will take timed input in Python. Then, handle the errors using except block and declare the timeout statement. Finally, print the statement on timeout.

Python3




# Import the libraries inputimeout, TimeoutOccurred
from inputimeout import inputimeout
  
# Try block of code
# and handle errors
try:
  
    # Take timed input using inputimeout() function
    time_over = inputimeout(prompt='Name your best friend:', timeout=3)
  
# Catch the timeout error
except Exception:
  
    # Declare the timeout statement
    time_over = 'Your time is over!'
    print(time_over)
  
# Print the statement on timeoutprint(time_over)


Output: 

How to set an input time limit in Python

 

Set an Input Time Limit using the select module

Select: This module that provides a connection to platform-specific input-output monitoring functions. You can install the select module in Python through the following command:

pip install select

Example:

First of all, import the required libraries. Now, define the question or print any line if you want and return three new lists containing a subset of content. Here, you can also declare the time in seconds after which timeout is done and the statement is returned. Moreover, run the if-else loop where the if statement will read the input and print the result till the time is running. Finally, define the else statement to catch the timeout statement and print it.

Python3




# Import the libraries select, sys
import sys
import select
  
# Print the question or any line you want
print("Who is your best friend?")
print("\nYou have ten seconds to answer!")
  
# Return 3 new list containing subset of content
# with timeout after which statement returns
a, b, c = select.select([sys.stdin], [], [], 10)
  
# Run if statement till the time is running
if (a):
  
    # Read the input and print result
    print("\nYou stated your best friend name as: ",
          sys.stdin.readline().strip())
  
# Run else when time is over
else:
  
    # Print the timeout statement
    print("\nYour time got over")


Output:

How to set an input time limit in Python

 

Set an Input Time Limit using the signal module

Signal: This module receives information from the operating system and passes it to the program in the form of signals. The signal module can be installed by running the following command in Python.

pip install signal

Example:

First of all, import the required library. Now, define custom handlers to be executed on receiving the signal using the signal() function. Also, define an alarm clock for the delivery of signals using SIGALRM. Then, create a function to take the input from the user. In the function, run the try-except statement to take input and handle the errors if any. In the try block, print any line of your choice or the question to be answered and return the taken input from the user.

Moreover, create an alarm using the alarm() function with the time specified in seconds. Next, run the function time_input() to capture the input of the user. Later on, disable the alarm after success. Finally, print the result, i.e., the value inputted by the user.

Python3




# Import the library signal
import signal
  
# Define an alarm clock for delivery of signal
signal.signal(signal.SIGALRM, lambda signum,
              frame: print('\nYour time got over'))
  
  
# Create a function to input
def raw_input():
    # Create a try block to take the input
    try:
  
        # Print the question or line of choice
        print("Who is your best friend?")
        print("You have ten seconds to answer!")
  
        # Take input from user
        foo = input("Enter your name!!")
  
        # Return the input to print result
        return foo
  
    # Define except block to catch timeout exception
    except Exception:
        return
  
  
# Create an alarm using alarm function
# with timer
signal.alarm(10)
  
# Run the function to
# capture the input of user
user_input = raw_input()
  
# Disable the alarm after success
signal.alarm(0)
  
# Print the result input by user
print('You stated your best friend name as: ', user_input)


Output:

How to set an input time limit in Python

 

Set an Input Time Limit using the threading module

Threading: The Python module which allows various tasks to run at the same time is known as the Threading module. It has an entry, execution, and endpoint. The thread module has a timer() function, which delays a certain action to be performed.

pip install threading

Example:

Now, we will take the time in seconds as input from the user. This will be the time allocated to the user for answering the question. Then, print the question for which the user needs to give the answer. Now, set the timer using the Timer() function with the time specified by the user and a message to print when the time will be over. Then, we start the timer using the start() function. Further, give an alert message to the user about his time has started. Moreover, take the input from the user and store it in a variable. Finally, stop the timer using the cancel() function.

Python3




# Import the libraries
from threading import Timer
  
# Take seconds as integer input
# for the time limit per question
input_time = int(input("Set time limit in seconds: "))
  
# Print the question to display
print("Who is your best friend?")
  
# Set the timer for the specified time and call the
# function to print the message when time is over
t = Timer(input_time, lambda: print(
    "\nYour writing time is over!!\nEnter / to quit the program"))
  
# Start the timer
t.start()
  
# Print a message for user specifying number of seconds
print("You have", str(input_time), " seconds to write the answer")
  
# Get value from user
answer = input()
  
# Stop the timer
t.cancel()


Output:

How to set an input time limit in Python

 



Last Updated : 09 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads