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

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

sleep() en Python

La fonction sleep() suspend (attend) l'exécution du thread courant pendant la durée spécifiée en secondes.

Python a un module appelétimeLe module, qui fournit quelques fonctions utiles pour gérer les tâches liées au temps. L'une des fonctions couramment utilisées est sleep().

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

Example1:Python sleep()

import time
print("Immediatement afficher")
time.sleep(2.4)
print("2.4secondes après l'affichage ")

Le programme fonctionne comme suit :

  • "Immediatement afficher" est affiché

  • Pause (délai) d'exécution2.4secondes après.

  • Affichage de la sortie"2.4secondes après l'affichage" .

On peut voir à partir de l'exemple ci-dessus que sleep() prend un nombre en virgule flottante comme paramètre.

Dans Python 3.5Avant, le temps de pause réel peut être inférieur au paramètre spécifié pour la fonction time().

De Python 3.5Début, le temps de pause devra être d'au moins la durée spécifiée en secondes.

Example2:Création d'une horloge numérique en Python

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

Dans le programme ci-dessus, nous avons calculé et affiché l'infiniwhile bouclel'heure locale actuelle dans le1secondes. De même, il calculera et affichera l'heure locale actuelle. Ce processus continuera.

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
... .. ...

Voici une version améliorée du programme ci-dessus, légèrement modifiée.

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)

Les threads en Python

Avant de discuter du programme multithréad sleep(), parlons d'abord des processus et des threads.

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

Threads are subsets of processes. 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 is executed.

Please note thatt1andt2Running 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.