Petits exemples de code Python

De knowledge
Aller à la navigation Aller à la recherche

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.