The Wayback Machine - https://web.archive.org/web/20240623123440/https://www.geeksforgeeks.org/how-to-make-a-python-program-wait/
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.  



Similar Reads

Selenium Wait Commands - Implicit, Explicit, and Fluent Wait
Selenium Python is one of the great tools for testing automation. These days most web apps are using AJAX techniques. When a page is loaded by the browser, the elements within that page may load at different time intervals. This makes locating elements difficult: if an element is not yet present in the DOM, a locate function will raise an ElementNo
5 min read
Make Python Wait For a Pressed Key
Halting the execution until the occurrence of an event is a very common requirement in prompt-based programs. In earlier times, the presence of functions such as getch in C/C++ was almost necessary for the code to make the console stay up to display the output. Now such shortcomings of the compiler have been dealt with, and now such functions serve
3 min read
Python | os.wait() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.wait() method in Python is used by a process to wait for completion of a child process. This method returns a tuple containing i
2 min read
Python - Stop & Wait Implementation using CRC
Stop and wait protocol is an error control protocol, in this protocol the sender sends data packets one at a time and waits for positive acknowledgment from the receiver's side, if acknowledgment is received then the sender sends the next data packet else it'll resend the previous packet until a positive acknowledgment is not received. Note: To get
7 min read
Python Program to Make a Simple Calculator
Here we will be making a simple calculator in which we can perform basic arithmetic operations like addition, subtraction, multiplication, or division. Python Program to Make a Simple CalculatorCreate a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication, or division depending upon the user inp
4 min read
Program to make Indian Flag in Python | Step by Step
Here, We'll be making Indian Flag in Python using Spyder tool which is a part of Anaconda interface. It is the beginner's practice problem for python programmers. Prerequisite: The only prerequisite for this code is little knowledge of basic python programming. You may install anaconda from here if you don't have any interpreter for python. Approac
4 min read
Python3 Program to Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc”Changing the character at position 3 to 'a' and c
3 min read
Python3 Program for Minimum move to end operations to make all strings equal
Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.Examples: Input : n = 2 arr[] = {"molzv", "lzvmo"} Output : 2 Explanation: In first string, we remove first element("m") from first string and append it end. Then we move second cha
2 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
three90RightbarBannerImg