4

I know of the print_slow function to make a print looks like a human typing. however, how can i make it print out instantly or skip the slow typing to show the print immediately by pressing a key or enter?

    import sys,time,random
def print_slow(str):
    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(0.05)

print_slow("Type something here slowly")

I have a sample code above, would anyone help me out?

  • Can't you just the builtin `print()` instead? – millimoose Jun 22 '18 at 15:46
  • Non-blocking keyboard input would be useful here, I bet. Take a look at [Polling the keyboard (detect a keypress) in python](https://stackoverflow.com/q/292095/953482). Then you can poll for the enter key, and break out of your loop early. – Kevin Jun 22 '18 at 15:51
  • As an aside, please be aware that `str` is a reserved word in Python, and shouldn't be used as a variable name. – TMarks Jun 22 '18 at 15:52
  • 1
    @TylerMarques - Your advice is sound, but I need to correct you on one small point. `str` is not a [reserved word](https://docs.python.org/3/reference/lexical_analysis.html#keywords). It is, however, a [built-in type](https://docs.python.org/3/library/functions.html#func-str). – Robᵩ Jun 22 '18 at 17:33
  • @Robᵩ Thanks for the correction. My mistake. – TMarks Jun 22 '18 at 18:43

1 Answers1

0

You need to use threading trick to simultaneously print and wait for user input. Have a look at this code (pressing Enter key will tell program to print fast):

from threading import Thread
waiting_time = 0.05
def check():
    i = input()
    global waiting_time
    waiting_time = 0
Thread(target = check).start()

import sys,time,random

def print_slow(str):

    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(waiting_time)

print_slow("Type something here slowly")
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
  • The modification of a variable without synchronization is making me so uneasy, even though Python's GIL probably makes this work right. – millimoose Jun 22 '18 at 16:23