I created a function that contains two nested functions. First I declare a variable "done"= False that is what would trigger the slow text print to skip and fully print the whole text. The first function, "checking", is for checking if a key has been pressed. I do this with the windows specific function msvcrt. If it logs a key stroke it updates the variable "done" to True. Then I use threading to run this function. Then I set up a second function where I print the passed text at different speeds and if the previous defined "done" variable is True then it clears the screen and prints the the text completely. However, probably due to the scope of the "done" variable, the done in the printing function never changes and so regardless of the key press being logged the text doesn't skip. I've tried adding global done to different parts but it still doesn't work and I'm not sure where to go from here.

import time, threading, os, sysimport msvcrt
def slow_print_interrupt(phrase, speed=0.07):
    global done
    done = False # this acts as the kill switch, using if statements, you can make certain button presses stop the message printing and outright display it
    def check_key():
        global done
        if msvcrt.kbhit(): #if a key press is recognized then done is changed to true
            done = True
            return done
    
    t = threading.Thread(target=check_key()) # Check key is running threading while the script prints
    t.start()
    
    def type_out():
        global done
        for char in phrase:
            if done:   #if done gets changed to true due to the check key function 
                os.system('cls')  #clears the command screen and then prints the phrase completely
                print(phrase)
                break
            sys.stdout.write(char)
            sys.stdout.flush()
            time.sleep(speed)
    
  
    type_out()
slow_print_interrupt("Hello this is a test. Pressing 'a' will end this and immediately display the message")
slow_print_interrupt('here is another sentence to test it')
1

There are 1 best solutions below

1
Cole Kaplan On

Instead of avoiding booleans being pass by reference by using global, try to use an object instead. This article talks about how to solve your task with a Queue.

https://superfastpython.com/thread-share-variables/