PyCharm print end='\r' statement not working

18,353

Solution 1

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

Solution 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)
Share:
18,353

Related videos on Youtube

HansSnah
Author by

HansSnah

Updated on June 06, 2022

Comments

  • HansSnah
    HansSnah about 2 years

    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?

    • Mark Perryman
      Mark Perryman over 8 years
      I don't think that you can rely on the behaviour of "\r". See stackoverflow.com/a/1761086/5568445
    • tobias_k
      tobias_k over 8 years
      Have you tried flushing at the end? print(..., flush=True)
    • HansSnah
      HansSnah over 8 years
      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 ;)
    • tobias_k
      tobias_k over 8 years
      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?
    • HansSnah
      HansSnah over 8 years
      I am running Python 3.5.1 😊
    • Aemyl
      Aemyl about 6 years
      I'm using PyCharm 2018.1 Community Edition on Windows 10 and a combination of the accepted answer and flush=True worked for me.
    • Adam Howell
      Adam Howell almost 3 years
      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.
  • StarSweeper
    StarSweeper over 6 years
    YES! The first solution worked for me using PyCharm and Python3
  • Russ Schultz
    Russ Schultz about 6 years
    for what it's worth, I coudn't get it to work for me. Windows 7, Python 3.6.3, PyCharm 2017.2.4 community
  • Russ Schultz
    Russ Schultz about 6 years
    for what it's worth, I coudn't get it to work for me. Windows 7, Python 3.6.3, PyCharm 2017.2.4 community