English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriales básicos de Python

Control de flujo de Python

Funciones en Python

Tipos de datos en Python

Operaciones de archivos de Python

Objetos y clases de Python

Fecha y hora de Python

Conocimientos avanzados de Python

Manual de Python

sleep() en Python

La función sleep() en Python detiene (espera) la ejecución del hilo actual durante la cantidad de segundos especificados.

Python tiene un módulo llamadotimeEl módulo, que proporciona algunas funciones útiles para manejar tareas relacionadas con el tiempo. Una de las funciones más comunes es sleep().

The sleep() function pauses the execution of the current thread for the specified number of seconds.

Example1:Python sleep()

import time
print("Immediate print")
time.sleep(2.4)
print("2.4después de segundos imprime ")

El funcionamiento del programa es el siguiente:

  • "Immediate print" se imprime

  • Pausa (retardo) de ejecución2.4después de segundos.

  • Imprimir salida"2.4después de segundos imprime" .

Desde el ejemplo anterior, se puede ver que sleep() toma un número de punto flotante como parámetro.

En Python 3.5Antes,el tiempo de pausa real puede ser menor que el parámetro especificado para la función time().

Desde Python 3.5Inicio,el tiempo de pausa será al menos la cantidad de segundos especificados.

Example2:Python crea un reloj digital

import time
while True:
  localtime = time.localtime()
  result = time.strftime("%I:%M:%S %p", localtime)
  print(result)
  time.sleep(1)

En el programa anterior, calculamos e imprimimos el tiempo infinitowhile循环la hora local actual dentro de1segundos. Del mismo modo, se calculará e imprimirá la hora local actual. Este proceso continuará.

When you run the program, the output will be similar to:

02:10:50 PM
02:10:51 PM
02:10:52 PM
02:10:53 PM
02:10:54 PM
... .. ...

Esta es una versión mejorada ligeramente modificada del programa anterior.

import time
while True:
  localtime = time.localtime()
  result = time.strftime("%I:%M:%S %p", localtime)
  print(result, end="", flush=True)
  print("\r", end="", flush=True)
  time.sleep(1)

Multihilo en Python

Antes de discutir sobre programas multihilo de sleep(), hablemos de procesos y hilos.

A computer program is a set of instructions. A process is the execution of these instructions.

A thread is a subset of a process. A process can have one or more threads.

Example3: Python multi-threading

All the programs above are single-threaded programs. This is an example of a multi-threaded Python program.

import threading 
  
def print_hello_three_times():
  for i in range(3)
    print("Hello")
  
def print_hi_three_times(): 
    for i in range(3) 
      print("Hi") 
t1 = thread.Thread(target=print_hello_three_times)  
t2 = thread.Thread(target=print_hi_three_times)  
t1.start()
t2.start()

When you run the program, the output will be similar to:

Hello
Hello
Hi
Hello
Hi
Hi

The above program has two threadst1andt2. These threads use t1.start() and t2.start() statement runs.

Please note thatt1andt2When running simultaneously, you may get different outputs.

: time.sleep() in multi-threaded programs

The sleep() function pauses the execution of the current thread for the specified number of seconds.

If it is a single-threaded program, sleep() will stop the execution of the thread and process. However, this function suspends the thread rather than the entire process in a multi-threaded program.

Example4: sleep() in multi-threaded programs

import threading 
import time
  
def print_hello():
  for i in range(4)
    time.sleep(0.5)
    print("Hello")
  
def print_hi(): 
    for i in range(4) 
      time.sleep(0.7)
      print("Hi") 
t1 = thread.Thread(target=print_hello)  
t2 = thread.Thread(target=print_hi)  
t1.start()
t2.start()

The above program has two threads. We have already used these two threads time.sleep(0.5) and time.sleep(0.75) its pause execution time is 0.5seconds and 0.7seconds.