Python: Print to one line with time delay between prints

Question:

I want to make (for fun) python print out ‘LOADING…’ to console. The twist is that I want to print it out letter by letter with sleep time between them of 0.1 seconds (ish). So far I did this:

from time import sleep
print('L') ; sleep(0.1)
print('O') ; sleep(0.1)
print('A') ; sleep(0.1)
etc...

However that prints it to separate lines each.

Also I cant just type print('LOADING...') since it will print instantaneously, not letter by letter with sleep(0.1) in between.

The example is trivial but it raises a more general question: Is it possible to print multiple strings to one line with other function being executed in between the string prints?

Asked By: MarcinKonowalczyk

||

Answers:

In Python2, if you put a comma after the string, print does not add a new line. However, the output may be buffered, so to see the character printed slowly, you may also need to flush stdout:

from time import sleep
import sys
print 'L',
sys.stdout.flush()
sleep(0.1)

So to print some text slowly, you could use a for-loop like this:

from time import sleep
import sys

def print_slowly(text):
    for c in text:
        print c,
        sys.stdout.flush()
        sleep(0.5)

print_slowly('LOA')

In Python3, change

print c,

to

print(c, end='')
Answered By: unutbu

Updated to print all the letters on one line.

from time import sleep
import sys
sys.stdout.write ('L') ; sleep(0.1)
sys.stdout.write ('O') ; sleep(0.1)
sys.stdout.write ('A') ; sleep(0.1)
...
sys.stdout.write ('n')

etc…

or even:

from time import sleep
import sys
output = 'LOA...'
for char in output:
    sys.stdout.write ('%s' % char)
    sleep (0.1)

sys.stdout.write ('n')
Answered By: Brenda J. Butler

To type a string one letter at a time all you’ve got to do is this:

import sys 
import time

yourWords = "whatever you want to type letter by letter"

for char in yourWords:
sys.stdout.write(char)
time.sleep(0.1)
Answered By: Perrin

You can also simply try this

from time import sleep
loading = 'LOADING...'
for i in range(10):
    print(loading[i], sep=' ', end=' ', flush=True); sleep(0.5)
Answered By: Zeeshan Rizvi
from time import sleep

myList = ['Let this be the first line', 'Followed by a second line', 'and a third line']

for s in myList:
    print(s) ; sleep(0.6)
Answered By: G. Trialonis
import time
import sys

def code(text, delay=0.07):
    for c in text:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(delay)
    print() 

Instead of print type code

Answered By: Ish

If you’ve written a quite large program and want to add that feature, then overwrite the builtin function print

python_print = print
def print(txt):
    text = str(txt)
    for c in text:
        python_print(c, end="", flush=True)
        time.sleep(random.randint(2, 8)/100)
    python_print()

This function ensures that

  1. The output is flushed (no need of the sys module)
  2. After one character was written, there is a delay of 0.02 to 0.08 seconds.
  3. The actual behavior of the print function is kept (so you can make it print arrays and modules) – because of the str() call, though there are some exceptions.

What this function cannot do:

You can’t call print like this anymore because it only takes one argument:

print("Hello", "World")

Feel free to add that feature or have a look at someone implemented that:
https://book.pythontips.com/en/latest/args_and_kwargs.html

Oh and if you haven’t noticed yet – use python_print() if delayed text is inapropriate in some cases.

I wonder why python_print is not shallow-cloned. May anyone explain?

Someone implemented that 🙂

Someone has called my approach (I think especially the *args) cute and worked for at least 30 minutes to get something even better which is considerably larger (please, don’t call it bloated though). I didn’t test it, but it seems working well to my eyes.

So with that code you’ll be able to use print like print("Hello", "World") again.

Credits to: @MarcinKonowalczyk =>
https://gist.github.com/MarcinKonowalczyk/48a08fe2492b88df184decf427fd2caf

Thank you for taking your time.

Now Run a Function While Loading

In order to run something (otherwise Loading would be useless anyway I guess) while it’s printing, you can use the threading module.

So, without further ado, let’s quickly get started.

import threading

def load():
  # do I/O blocking stuff here

threading.Thread(target=load).start() # returns the thread object 
# and runs start() to launch the function load() non-blocking.
print("LOADING...")

You may consider removing the random delay from my function which is untypical for a LOADING... screen.

If you don’t need to wait until the LOADING… is done to close the program easily with ctrl-c, you can change the daemon attribute to True. Please note that, if the main thread finishes, your other thread will stop forcefully.

Here’s an example to how you could to that:

loadingThread = Threading.thread(target=load)
loadingThread.daemon = True
loadingThread.start()

print("LOADING...")
loadingThread.join() # wait for the loadingThread to finish

With this, the program will exit just fine, however you may have to catch KeyboardInterrupt:

try:
    loadingThread.join()
except KeyboardInterrupt:
    # cleanup stuff here or just *pass*
finally: # optional, runs *always*
    # cleanup stuff here
Answered By: france1