Python3 how to clear previous prints while looping, flush? [duplicate] - python

This question already has answers here:
Replace console output in Python
(12 answers)
Closed 2 years ago.
I want to show only one item at the screen I guess this should be done with print(..., flush=True) but it don't work as I expected.
for i in range(0,100):
print(i, end='', flush=True)
Now I get a numbers like this 012345678.... and what I want to see at the screen is only one number without seeing previous prints so with first iteration it shows only 0 second shows only 1, I thought flush would do the trick but it didn't so where am I wrong?

You can use end='\r' as an argument to print(). \r escape sequence moves the cursor to the starting of the line. flush is not the correct argument for doing this.
Your code can be:
for i in range(0,100):
print(i, end='\r')

You can make use of os module to do the same
import os
import time
for i in range(100):
print(i)
time.sleep(1)
os.system("clear") # For Linux
#os.system("cls") # For Windows
I have used time.sleep() to make sure the effect is visible otherwise it executes very fast. You may make variations as per the need.

Related

Sleep function not working after program is saved [duplicate]

This question already has answers here:
How can I flush the output of the print function?
(13 answers)
Closed 1 year ago.
I am using a time.sleep function to have my strings printed letter by letter, and it works perfectly while running inside pycharm, yet when I save the program and run it directly, the function does not take effect
def welcome():
greeting = random.choice(open_msg)
for i in range(len(greeting)):
print(greeting[i], end='')
time.sleep(0.15)
This is an example of what the code looks like
By default, Python's output is line-buffered. Therefore it won't print anything until you print a linefeed. To avoid this behavior, flush the output after each letter. Since Python 3.3, print() has an argument to do this. (For older versions, you need to sys.stdout.flush() after each print().)
print(greeting[i], end='', flush=True)
You can cause Python not to buffer by invoking it with the -u flag or by setting the environment variable PYTHONUNBUFFERED to any value. But these affect all output. It's better to use flush where you need it and leave other output buffered, because buffered is faster.
By the way, don't use range() when iterating over a string. Iterate over the string directly and you get the characters.
for c in greeting:
print(c, end='', flush=True)
# etc.
Ides can take longer to execute, amplifying the time.sleep() function
Maybe lengthen the time in the argument of time.sleep()
It should be working. Perhaps you forgot one of your imports? If so, here is the code, it is written well.
import random
import time
open_msg = ['hello', 'finished', 'chicken']
def welcome():
greeting = random.choice(open_msg)
for i in range(len(greeting)):
print(greeting[i], end='' )
time.sleep(0.15)
welcome()
``

time.sleep not working per item in range or list [duplicate]

This question already has answers here:
How can I flush the output of the print function?
(13 answers)
Closed 2 years ago.
I was trying to make a code like this
def no(t=.001):
print("N", end='')
for i in range(1000):
print('o', end='')
time.sleep(t)
print()
So that when I call no() I would print a long "Nooooo...", waiting some time between each 'o'.
What happens instead is that the function halts, for the whole total time (1 second with the default argument), then prints the whole list.
Is this intended? And if not how should I obtain my intended effect?
What's happening here is that python is actually printing all the characters in exactly the same way that you intend - it writes the N, then an o per second to stdout. The issue is that the operating system does not display it because the file (stdout is a file) is not flushed. This typically automatically happens when \n is printed (by default, at the end of the printed string), but you'd overwritten that with end==''.
Luckily, print has an optional flush argument that you can use to force a flush. So you should be able to fix your behavior with this:
def no(t=.001):
print("N", end='', flush=True)
for i in range(1000):
print('o', end='', flush=True)
time.sleep(t)
print()

Making a delay between typed characters [duplicate]

This question already has answers here:
How can I flush the output of the print function?
(13 answers)
Closed 4 years ago.
First, look at this:
import time
wait = time.sleep
def put(char):
print(char, end='')
def text(*pieces):
for p in pieces:
for c in p:
put(p)
wait(0.25)
I wanted to make a function that prints characters one by one with a delay of 250ms. But the problem is, it doesn't actually print characters one by one, instead, nothing happens until the "for" loop ends, then the given pieces of text is printed directly at once. Can someone tell me another way to do that, as in Undertale, typing/printing/putting characters one by one with a delay? Thanks.
You need to add flush=True to your print statement, otherwise the system will wait till the for loop is done. Note: this is only done if you're printing with end=''.
wait = time.sleep
def put(char):
print(char, end='', flush=True)
def text(pieces):
print(pieces)
for p in pieces:
put(p)
wait(0.25)
text('arsasrtrasars')

print without new line only appear after I write something else [duplicate]

This question already has answers here:
Printing on the same line with time.sleep()
(2 answers)
Closed 8 years ago.
I'm using Python 2.7.3 and I running the code below
def t2():
print "Waiting...",
time.sleep(3)
print "done."
time.sleep(1)
print "test"
time.sleep(2)
print "testing"
When I run this code, the string "Waiting... done." appear at same time. It's like the sleep(2) is before the first print.
If I don't use comma to remove new line (Like "test" and "testing" examples), sleep function works ok but I get "Waiting..." and "done." on different lines.
I already tried:
for i in range(0, 5): time.sleep(1)
and
subprocess.check_output(["sleep", "5"])
What can I do?
Thank you.
Depending what you are working with data doesn't necessarily get written right away. In particular,
display output often waits until it receives a newline before printing anything.
flush() makes sure it all gets written right now.
Background reading that helps explain better than I can:
Usage of sys.stdout.flush() method

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