Delaying Execution in Python with time.sleep()
A common need in Python scripts is to introduce a time delay, such as for intervals between tasks or pausing for user input. This can be achieved using the time.sleep() function.
To implement a delay, specify the desired amount of time (in seconds) as the argument to time.sleep(). For example, to delay execution by 2.5 seconds:
import time time.sleep(2.5)
This will cause the script to pause for the specified duration before continuing to the next line of code.
Alternatively, to execute a task at regular intervals, employ a loop with a delay:
import time while True: print("This prints once a minute.") time.sleep(60) # Delay for 1 minute (60 seconds).
In this example, the loop will continuously print a message every minute, with the delay provided by time.sleep(60).
The above is the detailed content of How Can I Pause My Python Script's Execution for a Specific Duration?. For more information, please follow other related articles on the PHP Chinese website!