Last active
January 5, 2023 10:49
-
-
Save MarcinKonowalczyk/48a08fe2492b88df184decf427fd2caf to your computer and use it in GitHub Desktop.
Slow print
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time, random | |
__python_print = print # save the original print function | |
def typed_print(*values, sep=' ', end='\n', file=None, flush=True): | |
""" Prints the values with a random delay between each character to make it look like it is being typed. The flush parameter must be True for this to work, otherwise it will just use the normal print function. """ | |
if flush == False: | |
# without flush this wont work so just use the normal print | |
__python_print(*values, sep=sep, end=end, file=file, flush=flush) | |
return | |
text = sep.join(str(v) for v in values) # join the values with the separator | |
for c in text: | |
__python_print(c, sep="", end="", file=file, flush=True) # print each character | |
time.sleep(random.randint(20, 80) / 1000) # sleep for a random amount of time to simulate typing | |
if end: | |
__python_print(end, sep="", end="", file=file, flush=True) # print the end | |
def patch_print(): | |
""" Patches the print function to use the typed_print function. """ | |
global print | |
print = typed_print | |
def unpatch_print(): | |
""" Unpatches the print function to use the original print function. """ | |
global print | |
print = __python_print | |
if __name__ == "__main__": | |
lorem_ipsum = "Hello, world! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ut arcu id est facilisis blandit." | |
print(lorem_ipsum) # normal print | |
patch_print() | |
print(lorem_ipsum) # patched print (print is now typed_print) | |
unpatch_print() | |
print(lorem_ipsum) # unpatched print (print is now __python_print) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Made in response to https://stackoverflow.com/a/75016243/2531987