Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slow, word-by-word terminal printing in Python? [duplicate]

I'm writing a Python app involving a database. For the hell of it, I'm including an easter egg. If the user decides to nuke his database, all this from a terminal, he'll be prompted to confirm with a simple (y/n). But if he types DLG2209TVX instead, the lines from that scene of WarGames will print. Doubt anybody will ever find it unless they look through my source, but that's okay.

The problem is that simply printing the lines plays the scene way too fast and really just ruins it. I implemented a timer between each character's lines to slow things down, and it's better, but it still seems unnatural. Is there a standardized way to slowly print each word or character out instead of doing it lines at a time? Or should I just start adding timers between words?

like image 881
Dylan Taylor Avatar asked Nov 17 '25 10:11

Dylan Taylor


2 Answers

Standardized? Not that I know of. But try this:

import random
import sys
import time

def slowprint(s):
    for c in s + '\n':
        sys.stdout.write(c)
        sys.stdout.flush() # defeat buffering
        time.sleep(random.random() * 0.1)

slowprint('Hello, world.')

Adjust the 0.1 to change the maximum delay between characters, and add lengthy time.sleep()s between lines to add more dramatic effect.

like image 99
zigg Avatar answered Nov 19 '25 23:11

zigg


import sys
import time
for c in gettysburg_address:
  sys.stdout.write(c)
  sys.stdout.flush()
  # 110 baud:
  time.sleep( 8./110 )
  # 300 baud:
  #  time.sleep( 8./300 )
like image 27
Robᵩ Avatar answered Nov 19 '25 23:11

Robᵩ