Print updating variable in the same line [duplicate] - python

This question already has answers here:
How do I write output in same place on the console?
(9 answers)
Closed 6 years ago.
What I'm trying to code is pretty simple:
I want to print an iteration variable, but I don't want all the lines printed for each loop, I want that will update the previous one.
Example:
for i in range(0,2000):
print 'number is %d', %i
Wrong result:
number is 0
number is 1
number is 2
number is 3
number is 4
number is 5
number is 6
...
...
What I want is:
number is 0
At the second iteration:
number is 1 `(it will replace 0 and I don't want the previous 0 anymore).`
It will be something like updating percentage of something in only one line.
Does a function exist for it in Python?

This will do the trick, and update every 1 second:
import sys
import time
for i in range(0,2000):
sys.stdout.write('\rnumber is %d' %i)
sys.stdout.flush()
time.sleep(1)

You can try something from this thread on clearing the terminal, or something from the one that fuglede posted as duplicated.
The following code worked fine for me in a mac, but if you remove the time.sleep() it will just run so fast that you wont even see the prints.
import time, sys
for i in range(0, 20):
print 'Number is: %d' % i
time.sleep(.1)
sys.stderr.write("\x1b[2J\x1b[H")

What you want is called the Carriage Return, or \r
Use:
for i in range(0,2000):
print "number is %d \r" %i,
The spaces will keep the line clear from prior output.

Related

how to print at same line using end parameter? [duplicate]

This question already has answers here:
How to overwrite the previous print to stdout?
(18 answers)
Closed 5 days ago.
I'd like to print at same line for print statement inside a for loop using end= parameter. not sure which end parameter i can use.
For example, in below, for each time's print, only need to change str(i) and str(result), everything is the same.
for i in range(10):
result=i**2
print('iteration is'+str(i)+' with result of '+str(result))
Thanks
Use an empty end parameter and go back the length of the previous print
L=0
for i in range(3):
result=i**2
my_str = 'iteration is'+str(i)+' with result of '+str(result)
print('\b'*L + my_str, end='')
L= len(my_str)

Printing on only one line [duplicate]

This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Print in one line dynamically [duplicate]
(22 answers)
Closed 3 years ago.
I have a program that has to only print data onto one line.
What can I do to do this.
for i in range(10):
print(i)
Is it possible to print all of this on one line so it prints 0, erases the line, print 2, erases, etc..?
Use print(i,end="\r") to return to the start of the line and overwrite.
for i in range(10):
print(i,end=" ")
this is easiest way to print in one line.
in python 2.x:
from __future__ import print_function
for i in range(10):
print (i, end="")
in python 3.x
for i in range(10):
print (i, end="")
For this specific usecase you can do something like this:
print(*range(10))
And to update each character on the line you will need to use '\r' or the return character, that returns the position of the cursor to the beginning of the line. However, you need to be sure you count in the length of the strings you are printing, otherwise you will be overwriting only part of the string. A full proof solution will be:
import time
maxlen = 0
for i in range(12,-1,-1):
if len(str(i))>maxlen:
maxlen = len(str(i))
print(f'\r{str(i): <{maxlen}}',end = '')
time.sleep(2)
print('')
time part is added so that you can view the change. maxlen computes the maximum length string you are going to print and formats the string accordingly. Note: I have used f'strings, hence it would only work for Python 3.x

What is the code for accepting input values only if they are entered within 5 seconds? [duplicate]

This question already has answers here:
User input with a timeout, in a loop
(6 answers)
Closed 3 years ago.
I need help to write a code that accepts input only if the user enters it within 5 seconds of asking for input, else prints out a message saying "Too late" and ending the program.
Clearly the algorithm I've used to solve the problem isn't right. There is no increment in time unless the user gives an input in the code given.
# code for accepting input only if entered within 5 seconds
print("Enter value: ")
sec = 0
for sec in range(0, 6):
while sec==5:
print("too late")
time.sleep(1)
sec += 1
a=input()
As a simple approach, you could maybe do something like this:
as input halts execution, the time elapsed is calculated upon entering the answer, and compared to the limit (here 5 seconds by default).
If within the time limit, the answer is returned for further processing, otherwise, too late is printed and None silently returned.
import time
def timed_acceptance(limit=5):
start = time.time()
a = input('you have 5 seconds:')
end = time.time()
if end - start < limit:
return a
else:
print('too late')
timed_acceptance()
The problem is that input blocks until there is input to be read. What you're looking for is what is known as non-blocking IO, that returns nothing if there isn't anything to read immediately. Here is a discussion on how to solve that in python: https://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/

Python time.sleep method not working properly [duplicate]

This question already has answers here:
How to print one character at a time on one line?
(4 answers)
How to make it look like the computer is typing? [duplicate]
(1 answer)
Closed 5 years ago.
I have written this small code in Python. It should print every character in a string with a small sleeptime between them...
import time, sys
def writeText(string, t):
i = 0
while i < len(string):
sys.stdout.write(string[i])
time.sleep(float(t))
i += 1
writeText("Hello World", 0.5)
but it only prints the whole string after 0.5 seconds... I often have this issue but I haven't found a solution yet.
sys.stdout.flush() might solve your problem.
import time, sys
def writeText(string, t):
i = 0
while i < len(string):
sys.stdout.write(string[i])
time.sleep(float(t))
i += 1
sys.stdout.flush()
writeText("Hello World", 0.5)
You should add
sys.stdout.flush()
after writing, to force the output of the text.

Interpolate sleep() and print() in the same line inside a for loop using python 3 [duplicate]

This question already has answers here:
Problems with sys.stdout.write() with time.sleep() in a function
(2 answers)
Closed 6 years ago.
I was trying to print the result of a loop in the same line using python 3 and after reading Python: for loop - print on the same line I managed to do it.
for x in range(1,10):
print(x, end="")
The problem now is when I insert
time.sleep(2)
before the print.
I would like to print the first character, wait two seconds, then the second, wait two more seconds, etc.
Here the code:
for x in range(1,10):
time.sleep(2)
print(x, end="")
With that we wait 20 seconds (= 10*2) and only then the numbers are displayed. This is not what we expect.
What I should do to have the above expected behavior, namely wait 2 seconds, print first character, wait more 2 seconds, print second character, etc.
Output to stdout is line buffered, which means the buffer is not flushed until a newline is printed.
Explicitly flush the buffer each time you print:
print(x, end="", flush=True)
Demo:

Categories