I am a new Python user. I would like to delay execution for five seconds in a Python script. How do I add a time delay in Python on Unix/Linux? Is there a sleep command in python like the Unix/Linux sleep utility to suspend execution of a bash script?

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Python time
Est. reading time 1m
You need to import and use a module called time. This module provides various time-related functions for Python users.

Python sleep syntax

The syntax is as follows

import time

The time.sleep() suspend execution of a script for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

Example: Put delay in a Python script

Create a script called demo-sleep.py:

  1. #!/usr/bin/python
  2. # The following will run infinity times on screen till user hit CTRL+C
  3. # The program will sleep for 1 second before updating date and time again.
  5. import time
  7. print("*** Hit CTRL+C to stop ***")
  9. ## Star loop ##
  10. while True:
  11.     ### Show today's date and time ##
  12.     print("Current date & time " + time.strftime("%c"))
  14.     #### Delay for 1 seconds ####
  15.     time.sleep(1)

Save and close the file. Run it as follows:
$ chmod +x demo-sleep.py
$ ./demo-sleep.py

Sample outputs:

Fig.01: Python sleep() demo program output

  1. Set an infinite loop using while True: (line # 10)
  2. Get the current date and time using strftime() and display on screen (line # 12).
  3. Finally, add 1 second delay in a script using sleep(1) (line #15).
  4. Continue this procedure till user interrupts.

Python sleep() to add delay and capture CTRL+C for graceful exit

The signal.signal() function allows defining custom handlers to be executed when a signal is received.

# The following will run infinity times on screen till user hit CTRL+C
# The program will sleep for 1 second before updating date and time again.
import time
import signal
import sys, os
# capture CTRL + C or other signal here
def goodbye(signal, frame):
    print('CTRL-C detected. Goodbye, ' + os.environ['USER'] + '!')
# Handel interrupt from keyboard (CTRL + C) and call goodbye()
signal.signal(signal.SIGINT, goodbye)
print("*** Hit CTRL+C to stop ***")
## Star loop ##
while True:
    ### Show today's date and time ##
    print("Current date & time " + time.strftime("%c"))
    #### Delay for 1 seconds ####

Summing up

You learned about time module and capturing CTRL + C from keyboard in Python 2.x/3.x.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 4 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
4 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum