PyCharm print end='\\r' statement not work

2020-07-02 11:01发布

问题:

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?

回答1:

Try:

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


回答2:

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)