Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 651
q0987 Avatar asked Oct 10 '11 16:10

q0987


People also ask

How do I keep a cursor on the same line in Python?

The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.

How do you change the cursor to a new line in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

What does \r do in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.


2 Answers

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='') 
like image 87
NPE Avatar answered Oct 03 '22 09:10

NPE


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() 
like image 44
Petr Viktorin Avatar answered Oct 03 '22 11:10

Petr Viktorin