Sleep in python script

Python Sleep Function: How to Add Delays to Code

Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

This tutorial will teach you how to use the sleep() function from Python’s built-in time module to add time delays to code.

When you run a simple Python program, the code execution happens sequentially—one statement after the other—without any time delay. However, you may need to delay the execution of code in some cases. The sleep() function from Python built-in time module helps you do this.

In this tutorial, you’ll learn the syntax of using the sleep() function in Python and several examples to understand how it works. Let’s get started!

Syntax of Python time.sleep()

The time module, built into the Python standard library, provides several useful time-related functions. As a first step, import the time module into your working environment:

As the sleep() function is part of the time module, you can now access and use it with the following general syntax:

Here, n is the number of seconds to sleep. It can be an integer or a floating point number.

Читайте также:  Test

Sometimes the required delay may be a few milliseconds. In these cases, you can convert the duration in milliseconds to seconds and use it in the call to the sleep function. For example, if you want to introduce a delay of 100 milliseconds, you can specify it as 0.1 second: time.sleep(0.1) .

▶ You can also import only the sleep function from the time module:

If you use the above method for importing, you can then call the sleep() function directly—without using time.sleep() .

Now that you’ve learned the syntax of the Python sleep() function, let’s code examples to see the function in action. You can download the Python scripts used in this tutorial from the python-sleep folder in this GitHub repo. 👩🏽‍💻

Delay Code Execution with sleep()

As a first example, let’s use the sleep function to delay the execution of a simple Python program.

Delaying-Code-Execution

In the following code snippet:

  • The first print() statement is executed without any delay.
  • We then introduce a delay of 5 seconds using the sleep() function.
  • The second print() statement will be executed only after the sleep operation finishes.
# /python-sleep/simple_example.py import time print("Print now") time.sleep(5) print("Print after sleeping for 5 seconds")

Now run the simple_example.py file and observe the output:

YouTube video

Add Different Delays to a Code Block

In the previous example, we introduced a fixed delay of 5 seconds between the execution of two print() statements. Next, let’s code another example to introduce different delay times when looping through an iterable.

In this example, we would like to do the following:

  • Loop through a sentence, access each word, and print it out.
  • After printing out each word, we’d like to wait for a specific duration of time—before printing out the next word in the sentence.

Looping Through a String of Strings

Consider the string, sentence . It is a string where each word is a string in itself.

If we loop through the string, we will get each character, as shown:

>>> sentence = "How long will this take?" >>> for char in sentence: . print(char) # Output (truncated for readability) H o w . . . t a k e ?

But this is not what we want. We would like to loop through the sentence and access each word. To do this, we can call the split() method on the sentence string. This will return a list of strings—obtained by splitting the sentence string—on all occurrences of whitespace.

>>> sentence.split() ['How', 'long', 'will', 'this', 'take?'] >>> for word in sentence.split(): . print(word) # Output How long will this take?

Looping Through Iterables with Different Delays

  • sentence is the string we’d like to loop through to access each word.
  • delay_times is the list of delay times we’ll use as argument to the sleep() function during each pass through the loop.

Here we would like to simultaneously loop through two lists: the delay_times list and the list of strings obtained by splitting the sentence string. You can use the zip() function to perform this parallel iteration.

The Python zip() Function: zip(list1, list2) returns an iterator of tuples, where each tuple contains the item at index i in list1 and list2.

# /python-sleep/delay_times.py import time sleep_times = [3,4,1.5,2,0.75] sentence = "How long will this take?" for sleep_time,word in zip(sleep_times,sentence.split()): print(word) time.sleep(sleep_time)

Without the sleep function, the control would immediately proceed to the next iteration. Because we have introduced a delay, the next pass through the loop occurs only after the sleep operation is complete.

Now run delay_times.py and observe the output:

The subsequent words in the string will be printed out after a delay. The delay after printing out the word at index i in the string is the number at index i in the delay_times list.

YouTube video

Countdown Timer in Python

As a next example, let us code a simple countdown timer in Python.

Countdown-Timer-in-Python

Let’s define a function countDown() :

# /python-sleep/countdown.py import time def countDown(n): for i in range(n,-1,-1): if i==0: print("Ready to go!") else: print(i) time.sleep(1)

Next, let’s parse the definition of the countDown() function:

  • The function takes in a number n as the argument and counts down to zero starting from that number n .
  • We use time.sleep(1) to achieve a delay of one second between the counts.
  • When the count reaches 0, the function prints out “Ready to go!”.

🎯 To achieve the countdown operation, we’ve used the range() function with a negative step value of -1. range(n, -1, -1) will help us loop through the range of numbers in n, n – 1, n – 2, and so on up to zero. Recall that the end point is excluded by default when using the range() function.

Next let’s add a call to the countDown() function with 5 as the argument.

Now run the script countdown.py and see the countDown function in action!

YouTube video

Sleep Function in Multithreading

Python threading module offers out-of-the-box multithreading capabilities. In Python, the Global Interpreter Lock or GIL ensures that there is only one active thread running at any point in time.

python-sleep-3

However, during I/O operations and wait operations such as sleep, the processor can suspend the execution of the current thread and switch to another thread that is waiting.

To understand how this works, let’s take an example.

Creating and Running Threads in Python

Consider the following functions, func1() , func2() , and func3() . They loop through a range of numbers and print them out. This is followed by a sleep operation—for a specific number of seconds—during every pass through the loop. We’ve used different delay times for each of the functions to better understand how the execution switches between threads concurrently.

import time def func1(): for i in range(5): print(f"Running t1, print .") time.sleep(2) def func2(): for i in range(5): print(f"Running t2, print .") time.sleep(1) def func3(): for i in range(4): print(f"Running t3, print .") time.sleep(0.5)

In Python, you can use the Thread() constructor to instantiate a thread object. Using the syntax threading.Thread(target = …, args = …) creates a thread that runs the target function with the argument specified in the args tuple.

In this example the functions, func1 , func2 , and func3 , do not take in any arguments. So it suffices to specify only the name of the function as the target. We then define thread objects, t1 , t2 , and t3 with func1 , func2 , and func3 as the targets, respectively.

t1 = threading.Thread(target=func1) t2 = threading.Thread(target=func2) t3 = threading.Thread(target=func3) t1.start() t2.start() t3.start()

Here’s the complete code for the threading example:

# /python-sleep/threads.py import time import threading def func1(): for i in range(5): print(f"Running t1, print .") time.sleep(2) def func2(): for i in range(5): print(f"Running t2, print .") time.sleep(1) def func3(): for i in range(4): print(f"Running t3, print .") time.sleep(0.5) t1 = threading.Thread(target=func1) t2 = threading.Thread(target=func2) t3 = threading.Thread(target=func3) t1.start() t2.start() t3.start()

Observe the output. The execution alters between the three threads. The thread t3 has the lowest waiting time, so it is suspended for the least amount of time. Thread t1 has the longest sleep duration of two seconds, so it’s the last thread to finish execution.

YouTube video

To learn more, read the tutorial on the basics of multithreading in Python.

Conclusion

In this tutorial, you have learned how to use Python’s sleep() function to add time delays to code.

You can access the sleep() function from the built-in time module, time.sleep() . To delay execution by n seconds, use time.sleep(n) . Also, you’ve seen examples of delaying subsequent iterations in a loop by different values, countdown, and multithreading.

You may now explore more advanced capabilities of the time module. Want to work with dates and times in Python? In addition to the time module, you can leverage the functionality of the datetime and calendar modules.

Источник

Python time sleep()

Python time sleep()

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Hello everyone, hope you are learning python well. In this tutorial we will learn about python time sleep() method. Python sleep function belongs to the python time module that is already discussed earlier

Python time sleep

Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds. Notice that python time sleep function actually stops the execution of current thread only, not the whole program.

Python time sleep() function syntax

python time sleep, python sleep

Python sleep() is a method of python time module. So, first we have to import the time module then we can use this method. Way of using python sleep() function is: Here the argument of the sleep() method t is in seconds. That means, when the statement time.sleep(t) is executed then the next line of code will be executed after t seconds. See the following example:

# importing time module import time print("Before the sleep statement") time.sleep(5) print("After the sleep statement") 

If you run the above code then you will see that the second print executes after 5 seconds. So you can make delay in your code as necessary. The argument can be in floating value also to have more precise delay. For example you want to make delay for 100 milliseconds which is 0.1 seconds, as following:

import time time.sleep(0.100) 

Python sleep example

import time startTime = time.time() for i in range(0,5): print(i) # making delay for 1 second time.sleep(1) endTime = time.time() elapsedTime = endTime - startTime print("Elapsed Time = %s" % elapsedTime) 
0 1 2 3 4 Elapsed Time = 5.059988975524902 

Elapsed time is greater than 5 because each time in the for loop, execution is halted for 1 second. The extra time is because of the execution time of the program, operating system thread scheduling etc.

Different delay time of python sleep()

import time for i in [ .5, .1, 1, 2]: print("Waiting for %s" % i , end='') print(" seconds") time.sleep(i) 
Waiting for 0.5 seconds Waiting for 0.1 seconds Waiting for 1 seconds Waiting for 2 seconds 

Dramatic printing using sleep()

# importing time module import time message = "Hi. I am trying to create suspense" for i in message: # printing each character of the message print(i) time.sleep(0.3) 

If you run the above code then, you will see that after printing every character of the message it’s taking some time, which seems like dramatic.

Python thread sleep

Python time sleep() function is very important method for multithreading. Below is a simple example showing that the python time sleep function halts the execution of current thread only in multithreaded programming.

import time from threading import Thread class Worker(Thread): def run(self): for x in range(0, 11): print(x) time.sleep(1) class Waiter(Thread): def run(self): for x in range(100, 103): print(x) time.sleep(5) print("Staring Worker Thread") Worker().start() print("Starting Waiter Thread") Waiter().start() print("Done") 

python thread sleep, python time sleep multithreading, python sleep example thread

Below image shows the output produced by above python thread sleep example. From the output it’s very clear that only the threads are being stopped from execution and not the whole program by python time sleep function. That’s all about python time sleep function or python sleep function. Reference: StackOverFlow Post, API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Оцените статью