« Petits exemples de code Python » : différence entre les versions

De knowledge
Aller à la navigation Aller à la recherche
mAucun résumé des modifications
mAucun résumé des modifications
 
Ligne 4 : Ligne 4 :
Voici un petit programme python qui  affiche l'heure au centre de l'écran et attends l'appuy sur une touche.<syntaxhighlight lang="python3">
Voici un petit programme python qui  affiche l'heure au centre de l'écran et attends l'appuy sur une touche.<syntaxhighlight lang="python3">
#!/bin/python3
#!/bin/python3
import time
import time  
import sys
import sys
import select
import select
Ligne 10 : Ligne 10 :
import tty
import tty
import shutil
import shutil
import hashlib
hashcode="dcc07eeab919998abfedd85c8946b83754501d8d"




Ligne 17 : Ligne 20 :
rows = size.lines
rows = size.lines


# FORMAT
# FORMAT  
date_format="\u25C0 %Y-%m-%d %H:%M:%S \u25B6";
date_format=" \u25C0\u25C0  %Y-%m-%d   %H:%M:%S   \u25B6\u25B6 ";
# Calcul de la chaine
# Calcul de la chaine
ssize=len(time.strftime(date_format))
ssize=len(time.strftime(date_format))
Ligne 26 : Ligne 29 :
center_y = rows // 2
center_y = rows // 2


# Sauvegarder les paramètres du terminal
#  sleep_time  to ajuste animation
sleep_time=0.03
phase=0
 
# Sauvegarder les paramètres du terminal
fd = sys.stdin.fileno()
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
old_settings = termios.tcgetattr(fd)
tty.setcbreak(fd)  # Mode caractère par caractère
tty.setcbreak(fd)  # Mode caractère par caractère
print ("Sleep mode. Type any key to resume...")
time_start=time.time()
print ("\033[?25l\033[s",end="") # on desactive l'affichage du "carret" du curseur et on sauve sa position
time_stop=time_start+0.5
time_slice=time_stop-time_start
count=0
increment=1
   
 
print ("\033[?25l\033[s",end="")
try:
try:
    print ("\033[?25l\033[s",end="")
     while True:
     while True:
         if select.select([sys.stdin], [], [], 0)[0]: # Si une touche est pressée
         try:
             break # on sort du 'while'
            if select.select([sys.stdin], [], [], 0)[0]:
        print(f"\033[{center_y};{center_x}H", end="")
                key = sys.stdin.read(1)
        now = time.time()
                if key in ('q', 'Q', '\033'):              
        ts=time.localtime(now)
                    print(f"\033[{center_y-1};{center_x}H"+" "*ssize, end="")
        f=time.strftime("\033[103m\033[31m"+date_format+"\033[0m",ts)
                    print(f"\033[{center_y+1};{center_x}H"+" "*ssize, end="")
         print (f,end="",flush=True)
                    print(f"\033[{center_y};{center_x}H"+" "*ssize, end="")
        time.sleep(0.1)
                    print(f"\033[{center_y};{center_x}H\033[0mEnter code:______\033[6D",end="", flush=True)
                    code=input()
                    hash_input_code = hashlib.sha1(code.encode()).hexdigest()
                    if hash_input_code == hashcode:
                      break
                if key in ('t', 'T'):             
                    print(f"\033[{center_y-1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y+1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H\033[0m time slice:{time_slice:.5f} \033[6D",end="", flush=True)
                    code=input()
                if key in ('s', 'S'):
                    print(f"\033[{center_y-1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y+1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H\033[0m sleep:{sleep_time:.5f} \033[6D",end="", flush=True)
                    code=input()
                if key in ('p', 'P'):
                    print(f"\033[{center_y-1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y+1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H\033[0m phase:{phase:.5f} \033[6D",end="", flush=True)
                    code=input()
                   
                   
            print(f"\033[{center_y-1};{center_x}H\033[0m Screen lock 'q' or <esc> to exit", end="")
            print(f"\033[{center_y};{center_x}H", end="")
            now = time.time()
            ts=time.localtime(now)
            f=time.strftime("\033[103m\033[31m"+date_format+"\033[0m",ts)
            print (f,end="",flush=True)
           
            print(f"\033[{center_y+1};{center_x}H",end="")
            ## Ajust frequency
            if time_slice>0.95 and time_slice<1.05:         # > 95% Green
                print ("\033[92m",end="")               
            else:
                if time_slice>0.75 and time_slice<1.25:    # > 75% Yellow
                    print ("\033[93m",end="")
                else:
                    print ("\033[31m",end="")              # <75% red
     
            ## print time arrow
 
            print (" "*count,end="",flush=True)
            if increment > 0:
                print (f"-> ",end="",flush=True)
            else:
                print (f"<- ",end="",flush=True)
            time.sleep(sleep_time)
            count+=increment
            if count>=ssize-2:
                time_start=time.time()
                increment=-1
            if count<=0:
                time_stop=time.time()
                time_slice=abs(time_stop-time_start)
                if time_slice < 1:
                    t=time.time()
                    phase=t-int(t)
                    sleep_time+=0.001
                else: 
                    sleep_time-=0.001
                    if sleep_time<0:
                        sleep_time=0               
                increment=+1
            te=time.time()
        except KeyboardInterrupt:
            print("\007", end="", flush=True)
       
 
finally:
finally:
     termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)  # Restaurer terminal
     termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)  # Restaurer terminal
     print(f"\033[{center_y};{center_x}H"+" "*ssize, end="") # On se positionne au centre
     print(f"\033[{center_y-1};{center_x}H"+" "*ssize, end="")
 
     print(f"\033[{center_y};{center_x}H"+" "*ssize, end="")
     print("\033[u\033[?25h", end="") # Restaurer position curseur et on affiche le carret
     print(f"\033[{center_y+1};{center_x}H"+" "*ssize, end="")
     print("Sleep mode terminated")


    print("\033[u\033[?25h", end="")  # Restaurer position curseur
   
</syntaxhighlight>Le script s'autoexplique. On utilise le module [[Python date et heure#Le module time|time]] el des [[ANSI|codes ansi]].
</syntaxhighlight>Le script s'autoexplique. On utilise le module [[Python date et heure#Le module time|time]] el des [[ANSI|codes ansi]].



Version actuelle datée du 24 novembre 2025 à 09:12

Script pour éviter le delog automatique et afficher l'heure

Souvent les connexions à la console ssh ont un time-out d'inactivité très (trop) court.

Voici un petit programme python qui affiche l'heure au centre de l'écran et attends l'appuy sur une touche.

#!/bin/python3
import time 
import sys
import select
import termios
import tty
import shutil
import hashlib

hashcode="dcc07eeab919998abfedd85c8946b83754501d8d"


# Obtenir la taille du terminal
size = shutil.get_terminal_size()
cols = size.columns
rows = size.lines

# FORMAT 
date_format=" \u25C0\u25C0   %Y-%m-%d    %H:%M:%S   \u25B6\u25B6 ";
# Calcul de la chaine
ssize=len(time.strftime(date_format))

# Calculer la position centrale
center_x = (cols // 2)-(ssize//2)
center_y = rows // 2

#  sleep_time  to ajuste animation
sleep_time=0.03
phase=0

# Sauvegarder les paramètres du terminal
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setcbreak(fd)  # Mode caractère par caractère
time_start=time.time()
time_stop=time_start+0.5
time_slice=time_stop-time_start
count=0
increment=1 
    

print ("\033[?25l\033[s",end="")
try:
    while True:
        try:
            if select.select([sys.stdin], [], [], 0)[0]:
                key = sys.stdin.read(1)
                if key in ('q', 'Q', '\033'):             
                    print(f"\033[{center_y-1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y+1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H\033[0mEnter code:______\033[6D",end="", flush=True)
                    code=input()
                    hash_input_code = hashlib.sha1(code.encode()).hexdigest()
                    if hash_input_code == hashcode:
                       break
                if key in ('t', 'T'):               
                    print(f"\033[{center_y-1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y+1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H\033[0m time slice:{time_slice:.5f} \033[6D",end="", flush=True)
                    code=input()
                if key in ('s', 'S'):
                    print(f"\033[{center_y-1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y+1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H\033[0m sleep:{sleep_time:.5f} \033[6D",end="", flush=True)
                    code=input()
                if key in ('p', 'P'):
                    print(f"\033[{center_y-1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y+1};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H"+" "*ssize, end="")
                    print(f"\033[{center_y};{center_x}H\033[0m phase:{phase:.5f} \033[6D",end="", flush=True)
                    code=input()
                    
                    
            print(f"\033[{center_y-1};{center_x}H\033[0m Screen lock 'q' or <esc> to exit", end="")
            print(f"\033[{center_y};{center_x}H", end="")
            now = time.time()
            ts=time.localtime(now)
            f=time.strftime("\033[103m\033[31m"+date_format+"\033[0m",ts)
            print (f,end="",flush=True)
            
            print(f"\033[{center_y+1};{center_x}H",end="")
            ## Ajust frequency
            if time_slice>0.95 and time_slice<1.05:         # > 95% Green
                print ("\033[92m",end="")                
            else:
                if time_slice>0.75 and time_slice<1.25:     # > 75% Yellow
                    print ("\033[93m",end="")
                else:
                    print ("\033[31m",end="")               # <75% red
       
            ## print time arrow
  
            print (" "*count,end="",flush=True)
            if increment > 0:
                print (f"-> ",end="",flush=True)
            else:
                print (f"<- ",end="",flush=True)
            time.sleep(sleep_time)
            count+=increment
            if count>=ssize-2:
                time_start=time.time()
                increment=-1
            if count<=0:
                time_stop=time.time()
                time_slice=abs(time_stop-time_start)
                if time_slice < 1:
                    t=time.time()
                    phase=t-int(t)
                    sleep_time+=0.001
                else:   
                    sleep_time-=0.001
                    if sleep_time<0:
                        sleep_time=0                
                increment=+1
            te=time.time()
        except KeyboardInterrupt:
            print("\007", end="", flush=True)
        

finally:
    termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)  # Restaurer terminal
    print(f"\033[{center_y-1};{center_x}H"+" "*ssize, end="")
    print(f"\033[{center_y};{center_x}H"+" "*ssize, end="")
    print(f"\033[{center_y+1};{center_x}H"+" "*ssize, end="")

    print("\033[u\033[?25h", end="")  # Restaurer position curseur

Le script s'autoexplique. On utilise le module time el des codes ansi.

Image-slock.png

L'heure et la date s'affiche au milieu de l'écran avec le carret qui disparait. Si on tape une touche on remplace le texte jaune de la date par des espaces,le carret réapparait et le curseur revient là ou il était.

Si il y avait du texte sous la date comme c'est le cas dans cet exemple il sera perdu et remplacé par des espaces.