Skip to content

Instantly share code, notes, and snippets.

@MarcinKonowalczyk
Last active January 5, 2023 10:49
Show Gist options
  • Save MarcinKonowalczyk/48a08fe2492b88df184decf427fd2caf to your computer and use it in GitHub Desktop.
Save MarcinKonowalczyk/48a08fe2492b88df184decf427fd2caf to your computer and use it in GitHub Desktop.
Slow print
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)
@MarcinKonowalczyk
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment