25

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?

HansSnah
  • 2,160
  • 4
  • 18
  • 31
  • I don't think that you can rely on the behaviour of "\r". See http://stackoverflow.com/a/1761086/5568445 – Mark Perryman Jan 22 '16 at 15:30
  • 3
    Have you tried flushing at the end? `print(..., flush=True)` – tobias_k Jan 22 '16 at 16:02
  • Intersting...but unfortunately it does not help me. Is there maybe another way how I can make this work in PyCharm @tobias_k flush does not help ;) – HansSnah Jan 22 '16 at 16:33
  • I don't have PyCharm. Can you find out, what exact version of Python PyCharm is using? What does `import sys; print(sys.version)` show when run in PyCharm? – tobias_k Jan 22 '16 at 21:38
  • I am running Python 3.5.1 – HansSnah Jan 22 '16 at 23:11
  • 1
    I'm using PyCharm 2018.1 Community Edition on Windows 10 and a combination of the accepted answer _and_ `flush=True` worked for me. – Aemyl Apr 23 '18 at 17:39
  • Using PyCharm 2021.2 on Windows 10 with Python v3.9.2, what worked for me was including the `\r` at the beginning of each print string, and `end=''`. I did not need to include `flush=True`. – Adam Howell Aug 19 '21 at 17:50

2 Answers2

32

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='')
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
androst
  • 441
  • 4
  • 6
8

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)
Cory Smith
  • 141
  • 2
  • 1