Python: Print to one line with time delay between prints - python

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?

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='')

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)

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)

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
The output is flushed (no need of the sys module)
After one character was written, there is a delay of 0.02 to 0.08 seconds.
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

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')

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)

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

Related

Is there a way to remove prevous prints?

So i am currently trying to make something that will print . and remove it then print ..
and also remove it then print ... When i tried using sys module to remove the prevous text this was the output: lol [Ktest so it basically adds a [K to the next line.
I also tried using another method so instead of removing the prevous text it would just add onto it like:
import time
print("lol",end="")
time.sleep(1)
print("test")
it did work in IDLE but when i tried to use it by opening the file in the command promt it waited for 1 second and then just gave loltest without any delay between them. So nothing i found in the internet worked for me.
You may print with the keyword argument end to append the special character '\r' to the end of the line.
E.g.
import time
print(".", end='\r')
time.sleep(2)
print("..", end='\r')
time.sleep(2)
print("...", end='\r')
time.sleep(2)
'\r' is carriage return and will return to the start of the line in some terminals, from where you can overwrite the text you just printed. Note that the behaviour might differ between terminals though.
To print over the prvious print, you can use end="\r.
import time
print("lol", end="\r")
time.sleep(1)
print("test")
for i in range(4):
print("."*i, end="\r")
time.sleep(1)
You can use the os module to execute shell commands.
To clear the terminal, command required in windows is cls and for unix its clear
import os
os.system('cls' if os.name == 'nt' else 'clear')
If you don't want to clear previous terminal outputs you can use flexibility of print function or the carriage return as others denoted.
for _ in range(3):
print('.', end='')
time.sleep(1)
If you specifically want to print . then .. then ..., you don't need to remove the existing text; you can just print additional dots.
To make the dots actually appear one by one, you'll need to flush the buffers, using flush=True
import time
for _ in range(3):
print('.', end='', flush=True)
time.sleep(1)
print()
This has the advantage that it will work much more generally; almost any output method can do that, whereas ANSI codes or tricks with \r or clearing the screen depend on your hardware, operating system and various other things.
You can do it with ANSI escape codes, like this:
import sys, time
clear_line = '\x1b[1K\r'
print("lol", end="")
sys.stdout.flush() # to force printing the text above
time.sleep(1)
print(clear_line+"test") # Now lol replaced with test
Please note that ANSI codes you should use depend on the environment where the program is executing (platform, terminal, etc.).
Update: you may want to see the built-in curses module.

Printing in the Different Line in Python [duplicate]

This question already has an answer here:
sys.stdout.write no longer prints on next row
(1 answer)
Closed 2 years ago.
I'm trying to print the following code in different lines but it always prints in the same line. Can anyone help please.
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
delay_print("Hi there hope everything is fine.")
time.sleep(2)
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
delay_print("This is a mail.")
This is the output showing to me-
Hi there hope everything is fine.This is a mail.
How to print them like this-
Hi there hope everything is fine.
This is a mail.
Just add print("\n") after the for loop.
Functions are written when a particular task is to be done multiple times, declaring the same function is not needed just call it, and you are good to go!
Although you can put \n just in argument to function but better put it in function itself
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
print("\n")
Also, on a side note, you dont need to re decalre the delay_print function
You can do the same thing as below without defining a function two times
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
ime.sleep(0.05)
print("\n")
delay_print("Hi there hope everything is fine.")
time.sleep(2)
delay_print("This is a mail.")
You either want to use sys.stdout.writelines(), where you would pass a list of 1 value to, or you want to add in your delay_print() an end-of-line token as \r\n
Just add \n at the end of string in first delay_print() :
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.05)
delay_print("Hi there hope everything is fine.\n") # like this .
time.sleep(2)
delay_print("This is a mail.")

printing to multiple lines at the same time python

I am making a text based game and I am trying to print this code one character at a time on each column.
'''###############
Let us begin...
###############'''
I can't figure out how to make it come out one column at a time.
Well, I still felt like answering this despite the vagueness of your question. Maybe this is what you are looking for, this prints one column at a time (one character per row):
import subprocess
import platform
from time import sleep
def clear_screen():
# thanks to: https://stackoverflow.com/a/23075152/2923937
if platform.system() == "Windows":
subprocess.Popen("cls", shell=True).communicate()
else:
print("\033c", end="")
# obviously you can create a function to convert your string into this
# list rather than doing it manually like I did, but that is another question :p.
views = ['#\nh\n#', '##\nhe\n##', '###\nhel\n###', '####\nhell\n####', '#####\nhello\n#####']
for view in views:
clear_screen()
print(view)
sleep(0.5)
If you are already doing print(c, end='') for each character in you string, just add flush=True to the call to print(). The sleep call will introduce enough delay so that you can see the characters print one at a time:
>>> import time
>>> s = '''###############
... Let us begin...
... ###############'''
>>> for c in s:
... print(c, end='', flush=True)
... time.sleep(0.1)

How can I print a string using a while loop with an interval in between letters (on the same line) in Python 3.2?

I am trying to print a string letter by letter (with a pause in between each print) onto the terminal screen and I want it to all be on the same line.
I currently have this:
sleepMode = "SLEEP MODE..."
activ = "ACTIVATE!"
for l in sleepMode:
print(l, end=" ")
sleep(0.1)
sleep(2)
for l in activ:
print(l, end=" ")
sleep(0.1)
For some reason this doesn't sleep in between prints in the loop, rather it seems to wait until the loop is complete before printing all of it out at once.
I want it to look like it is being "typed" on the screen in real time.
Any suggestions?
Thanks!
Zach
try flushing it
for l in activ:
print(l, end=" ")
sys.__stdout__.flush()
sleep(0.1)
no idea if it will work since I am assuming you are using py3x and it works fine in my system with or without the flush
flush just forces the output buffer to write to the screen ... normally it will wait until it has some free time to dump it to the screen. but sleep was locking it. so by flushing it you are forcing the content to the screen now instead of letting the internal scheduler do it ... at least thats how I understand it. Im probably missing some nuance
The following works:
import time
import sys
sleepMode = "SLEEP MODE..."
activ = "ACTIVATE!"
for l in sleepMode:
sys.stdout.write(l);
time.sleep(0.1)
time.sleep(2)
print
for l in activ:
sys.stdout.write(l);
time.sleep(0.1)

How to reset cursor to the beginning of the same line in Python

Most of questions related to this topics here in SO is as follows:
How to print some information on the same line without introducing a
new line
Q1 Q2.
Instead, my question is as follows:
I expect to see the following effect,
>> You have finished 10%
where the 10 keep increasing in the same time. I know how to do this in C++ but cannot
find a good solution in python.
import sys, time
for i in xrange(0, 101, 10):
print '\r>> You have finished %d%%' % i,
sys.stdout.flush()
time.sleep(2)
print
The \r is the carriage return. You need the comma at the end of the print statement to avoid automatic newline. Finally sys.stdout.flush() is needed to flush the buffer out to stdout.
For Python 3, you can use:
print("\r>> You have finished {}%".format(i), end='')
Python 3
You can use keyword arguments to print:
print('string', end='\r', flush=True)
end='\r' replaces the default end-of-line behavior with '\r'
flush=True flushes the buffer, making the printed text appear immediately.
Python 2
In 2.6+ you can use from __future__ import print_function at the start of the script to enable Python 3 behavior. Or use the old way:
Python's print puts a newline after each command, unless you suppress it with a trailing comma. So, the print command is:
print 'You have finished {0}%\r'.format(percentage),
Note the comma at the end.
Unfortunately, Python only sends the output to the terminal after a complete line. The above is not a complete line, so you need to flush it manually:
import sys
sys.stdout.flush()
On linux( and probably on windows) you can use curses module like this
import time
import curses
win = curses.initscr()
for i in range(100):
win.clear()
win.addstr("You have finished %d%%"%i)
win.refresh()
time.sleep(.1)
curses.endwin()
Benfit with curses as apposed to other simpler technique is that, you can draw on terminal like a graphics program, because curses provides moving to any x,y position e.g. below is a simple script which updates four views
import time
import curses
curses.initscr()
rows = 10
cols= 30
winlist = []
for r in range(2):
for c in range(2):
win = curses.newwin(rows, cols, r*rows, c*cols)
win.clear()
win.border()
winlist.append(win)
for i in range(100):
for win in winlist:
win.addstr(5,5,"You have finished - %d%%"%i)
win.refresh()
time.sleep(.05)
curses.endwin()
I had to combine a few answers above to make it work on Python 3.7 / Windows 10. The example runs on Spyder's console:
import sys, time
for i in range(0, 101, 5):
print("\r>> You have finished {}%".format(i), end='')
sys.stdout.flush()
time.sleep(.2)
The time.sleep(.2) is just used to simulates some time-consuming code.
using sys.stdout.write() instead of print works in both python 2 and 3 without any compromises.
The OP didn't specify Py2 or Py3. In Python 3 the 'import' of 'sys' and the 'sys.stdout' call can be replaced with 'flush=True':
import time
for i in range(0,101,25):
print("\r>>TESTING - {:0>3d}%".format(i), end='', flush=True)
time.sleep(.5)
print()
Thanks to Petr Viktorin for showing the "flush" parameter for Python 3 print(). I submit this because his Python 3 example doesn't include a 'format' specifier. It took me awhile to figure out that the additional parameters go after the 'format' specifier parentheses as shown in my example. I just picked an example format of 3 character integer 0 filled on the left. The best doc I found for Py3 format is: 6.1.3.1. Format Specification Mini-Language

Categories