Python time.sleep() to Pause, Sleep, Wait or Stop a Python Script

Pause Sleep Wait or Stop a Python Script

There is a useful function in Python called ‘sleep()’. It’s part of the ‘time’ module and allows you to pause, sleep, wait, or stop a Python script or application.

Python can be used to make useful command-line tools to streamline your workflow, but sometimes you need to wait for the user, or for a pre-defined amount of time.

For example, you may want to prompt the user to press a key when they have finished reading instructions or give them time to override a default action.

Pausing a Python Program by Waiting for User Input

This code snippet will wait until the user presses the enter Key.

print("Very important program output")
input("Press ENTER to continue.")
print("More very important program output")

Note that:

  • The code will run, wait for the user to press ENTER, and then continue running – in this case, it’s just printing text before and after the wait
  • input() will accept any input and is usually used for accepting user input to a variable
    • However, we’re using it to wait as it will only complete executing once the ENTER key is pressed, allowing the code following it to continue
    • As the result of input()* isn’t assigned to a variable, it’s discarded

Pausing for a Duration of Time using the time.sleep() Method

If you want to wait for a specified duration or number of seconds, you can use the sleep function from Python’s time module.

import time # Import the time module

print("Very important program output")
print('Before Pause: %s' % time.ctime())

time.sleep(6.6)    # Pause 6.6 seconds

print('After Pause: %s' % time.ctime())
print("More very important program output")
  • time.sleep(seconds) will pause execution for the given number of seconds
  • The time module must be imported first using import time
  • To show that things were paused for the correct duration, the result of the time.ctime() method was printed before and after time.sleep()
    • time.ctime() will return the current local time when it is run

Conclusion

Computers execute code very, very quickly – If you’re building interactive apps you’ll need to pause every now and then to let the user catch up!

Click here for more Python stuff!

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

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