Stampa l'output del codice al centro dello schermo


10

Il codice seguente mostrerà qualsiasi cosa fileparola per parola sullo schermo. Per esempio:

Hello verrà visualizzato per 1 secondo e scomparirà. Quindi, la parola successiva nella frase apparirà per un secondo e scomparirà e così via.

Come faccio ad emettere tutto ciò che viene visualizzato al centro dello schermo?

awk '{i=1; while(i<=NF){ print $((i++)); system("sleep 1; clear") }}' file

Che cosa stai cercando di ottenere esattamente?
Muru,

quel comando visualizza ogni parola da un file nell'angolo in alto a sinistra dello schermo. Devo sapere come realizzare l'output al centro dello schermo.
Nebelz Cheez,

4
Sì, ma cosa stai cercando di ottenere? Sembra un problema XY ,
Muru

Qual è il "centro di uno schermo"? Nel mezzo di un terminale? Il centro dello schermo reale? Che cosa succede se ridimensionate il terminale, ne avete bisogno per posizionare dinamicamente il testo nel mezzo qualunque dimensione abbia il vostro terminale?
terdon,

sì. La metà del terminale.
Nebelz Cheez,

Risposte:


7

Ecco uno script bash molto robusto:

#!/bin/bash

## When the program is interrupted, call the cleanup function
trap "cleanup; exit" SIGHUP SIGINT SIGTERM

## Check if file exists
[ -f "$1" ] || { echo "File not found!"; exit; }

function cleanup() {
    ## Restores the screen content
    tput rmcup

    ## Makes the cursor visible again
    tput cvvis
}

## Saves the screen contents
tput smcup

## Loop over all words
while read line
do
    ## Gets terminal width and height
    height=$(tput lines)
    width=$(tput cols)

    ## Gets the length of the current word
    line_length=${#line}

    ## Clears the screen
    clear

    ## Puts the cursor on the middle of the terminal (a bit more to the left, to center the word)
    tput cup "$((height/2))" "$((($width-$line_length)/2))"

    ## Hides the cursor
    tput civis

    ## Prints the word
    printf "$line"

    ## Sleeps one second
    sleep 1

## Passes the words separated by a newline to the loop
done < <(tr ' ' '\n' < "$1")

## When the program ends, call the cleanup function
cleanup

8

Prova lo script qui sotto. Rileverà la dimensione del terminale per ogni parola di input, quindi si aggiornerà anche in modo dinamico se ridimensionate il terminale mentre è in esecuzione.

#!/usr/bin/env bash

## Change the input file to have one word per line
tr ' ' '\n' < "$1" | 
## Read each word
while read word
do
    ## Get the terminal's dimensions
    height=$(tput lines)
    width=$(tput cols)
    ## Clear the terminal
    clear

    ## Set the cursor to the middle of the terminal
    tput cup "$((height/2))" "$((width/2))"

    ## Print the word. I add a newline just to avoid the blinking cursor
    printf "%s\n" "$word"
    sleep 1
done 

Salvalo come ~/bin/foo.sh, rendilo eseguibile ( chmod a+x ~/bin/foo.sh) e assegnagli il tuo file di input come primo argomento:

foo.sh file

3

funzione bash per fare lo stesso

mpt() { 
   clear ; 
   w=$(( `tput cols ` / 2 ));  
   h=$(( `tput lines` / 2 )); 
   tput cup $h;
   printf "%${w}s \n"  "$1"; tput cup $h;
   sleep 1;
   clear;  
}

e poi

mpt "Text to show"

1
Sembra esattamente la stessa della mia risposta, tranne per il fatto che mostra una cosa e non tutte le parole di una frase lette da un file separatamente, come richiesto dall'OP.
terdon,

1

Ecco lo script Python che è simile alla soluzione di @ Heliobash :

#!/usr/bin/env python
import fileinput
import signal
import sys
import time
from blessings import Terminal # $ pip install blessings

def signal_handler(*args):
    raise SystemExit

for signal_name in "SIGHUP SIGINT SIGTERM".split():
    signal.signal(getattr(signal, signal_name), signal_handler)

term = Terminal()
with term.hidden_cursor(), term.fullscreen():
    for line in fileinput.input(): # read from files on the command-line and/or stdin
        for word in line.split(): # whitespace-separated words
            # use up to date width/height (SIGWINCH support)
            with term.location((term.width - len(word)) // 2, term.height // 2):
                print(term.bold_white_on_black(word))
                time.sleep(1)
                print(term.clear)
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.