Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm print end='\r' statement not working

Tags:

python

pycharm

There are already lots of other questions about the print statement, but I have not found an answer to my problem:

When I do:

for idx in range(10):
    print(idx, end="\r")

in the (ipython) terminal directly, it works fine and always overwrites the previous line. However, when running this in a module with PyCharm, I don't see any lines printed in the stdout.

Is this a known PyCharm issue?

like image 426
HansSnah Avatar asked Jan 22 '16 15:01

HansSnah


People also ask

What does end \r do in Python?

Conceptually, \r moves the cursor to the beginning of the line and then keeps outputting characters as normal. You also need to tell print not to automatically put a newline character at the end of the string. In python3, you can use end="" as in this previous stackoverflow answer.

How to use end in Python print statement?

The end parameter in the print function is used to add any string. At the end of the output of the print statement in python. By default, the print function ends with a newline. Passing the whitespace to the end parameter (end=' ') indicates that the end character has to be identified by whitespace and not a newline.

How do you overwrite output in Python?

Approach. By default, Python's print statement ends each string that is passed into the function with a newline character, \n . This behavior can be overridden with the function's end parameter, which is the core of this method. Rather than ending the output with a newline, we use a carriage return.


2 Answers

Try to add \r at the beginning of your printed string (not at the end):

    for idx in range(10):
        print('\r', idx, end='')

Carriage return at front, and end with '' to avoid new line '\n'. One solution to avoid the space is to use the format convention:

    for idx in range(10):
        print("'\r{0}".format(idx), end='')
like image 60
androst Avatar answered Oct 06 '22 21:10

androst


I had the same issue. While a solution using print() has eluded me, I have found sys.stdout.write works fine. (Win10, Python 3.5.1, Pycharm 2016.3.2)

import sys
import time

def countdown(n):
    for x in reversed(range(n)):
        sys.stdout.write('\r' + str(x))
        time.sleep(1)

countdown(60)
like image 30
Cory Smith Avatar answered Oct 06 '22 21:10

Cory Smith