Open In App

How to make a Python program wait?

Last Updated : 14 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Have you ever encountered a scenario where you wanted your Python application to pause or run for a predetermined amount of time? You’re not by yourself. Python can pause its execution with the wait function, much like a well-timed comic, yet many coders find themselves in need of this feature. We’ll take you step-by-step through the Python wait function’s usage in this tutorial, covering both fundamental and sophisticated methods. We’ll go over everything, including how to use the time.sleep() function and more advanced applications like loops and threading.

Prerequisites:  

Some requirements require a Python program to wait before it goes on. We might need another function to complete or a file to load to give the user a better experience. Discussed below are some ways by which this can be achieved.

Different Wait Method in Python

There are various methods for Waiting in Python here we are discussing some generally used methods for waiting in Python, those are the following.

  1. Python Time Module
  2. Using Simple input()
  3. Using Keyboard Module
  4. Using Code Module
  5. Using OS Module

Make a Python Program wait using Time module

There are two methods to wait in Python using the time module, we are explaining both with examples methods following :

  1. General sleep function
  2. Sleep in multithreaded programming

1. Python Sleep Function Make a Python Program Wait

Python has a module named time. This module gives several useful functions to control time-related tasks. sleep() is one such function that suspends the execution of the calling thread for a given number of seconds and returns void. The argument may be a floating-point number to indicate more precise sleep time. This is the most common method used because of its ease of use and its platform-independent. The implementation is given below:

Example: In the example below Python code uses the `time` module to introduce a delay in the execution of the program. It immediately prints “GFG printed immediately,” then pauses for 5.5 seconds using `time.sleep(5.5)`, and finally prints “GFG printed after 5.5 secs.” after the delay.

Python3




# First import time module.
import time
 
# immediately prints the following.
print("GFG printed immediately.")
time.sleep(5.5)
 
# delays the execution
# for 5.5 secs.
print("GFG printed after 5.5 secs.")


Output:

2. Python make Program wait using Sleep in multithreaded programming

For multithreaded python programs, the sleep() function suspends the current thread for a given number of seconds rather than the whole process. But for single-threaded programs sleep() function suspends the thread and the whole process. The implementation is given below:

Example: In this example the below Python code uses two threads to concurrently print “GFG” and “Geeksforgeeks” in a loop, with different time delays between prints, achieved by the `time.sleep` function.

Python3




# import threading and time module.
import threading
import time
 
def print_GFG():
    for i in range(5):
        # suspend the current thread.
        time.sleep(1)
        print("GFG")
 
def print_Geeksforgeeks():
    for i in range(5):
        # suspend the current thread.
        time.sleep(1.5)
        print("Geeksforgeeks")
 
# two threads are available in this program.
t1 = threading.Thread(target=print_GFG)
t2 = threading.Thread(target=print_Geeksforgeeks)
t1.start()
t2.start()


Output:

Wait in Python using Simple Input()

We all know that the input() function helps to take data from users. But with the help of this function, we can also pause a python script until a certain key is pressed, like in the following code:

Example: In this example the below code prints “GFG immediately,” waits for the user to press Enter, and then prints “GFG after the input.”

Python3




print("GFG immediately")
i = input("Press Enter to continue: ")
 
# pauses the script here
# until the user press any key.
print("GFG after the input.")


Output:

Python wait using Keyboard Module

Using this module, we can resume the program by pressing the key that is specified in the python script (In this program the key is the ‘space key). Keyboard module doesn’t come in-built with python, thus needs to be installed explicitly using the following command:

pip install keyboard

The implementation is given below:

Example: In this example the below Python script utilizes the `keyboard` module to implement a pause function. It prints a message, halts execution until the ‘space’ key is pressed, and then continues with another message.

Python3




# import keyboard module.
import keyboard
 
# pause() function definition.
def pause():
    while True:
        if keyboard.read_key() == 'space':
            # If you put 'space' key
            # the program will resume.
            break
 
 
print("GeeksforGeeks printed before pause function")
pause()
print("GeeksforGeeks printed after pause function")


Output:

Make Python Wait using Code Module

This module contains a function called interact(). Some non-programmers may like this simple method. This creates an interpreter that acts almost exactly like a real interpreter. This creates a new instance of Interactive Console and sets readfunc to be used as the InteractiveConsole.raw_input() method if provided.

Example:

For the program given below press (Ctrl+D) to resume.

Python3




# import code
import code
 
print("GeeksforGeeks printed immediately.")
 
# implementation of code.interact().
code.interact(banner='Paused. Press ^D (Ctrl+D) to continue.', local=globals())
print("GeeksforGeeks.")


Output:

Python Program Wait using OS Module

Os module contains a method called system(“pause”). Using this method we can make a python program wait until some key is pressed. But this method is platform dependent i.e. only works on windows. So, it is not widely used.

Example: In this example the below Python code prints “GeeksforGeeks printed immediately.” to the console, pauses execution until the user presses a key, and then prints “GeeksforGeeks.”

Python3




import os
 
print("GeeksforGeeks printed immediately.")
os.system("pause")
print("GeeksforGeeks.")


Output:

Conclusion

From the simple time.sleep() to advanced threading techniques, you now hold the power to make your Python programs wait with grace and purpose. Remember, a well-timed pause can enhance user experience, improve program flow, and even add a touch of realism to your simulations.  



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads