Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When writing carriage return to a pycharm console the whole line is deleted?

I have a program in Python that makes extensive use of the line feed character to produce the effect of an updating console line (specifically a progress bar). When trying to debug the code in PyCharm I saw that the progress bar doesn't get printed until it's done.

Upon further inspection it turned out that when a carriage return (\r) is printed, the whole line is deleted. Because the library itself writes strings of the form ({line}\r), I always get an empty line.

Sample code:

import sys
sys.stdout.write('xxx')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('\rZZ')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('yyy\r')
sys.stdout.flush()

time.sleep(1)

print ('===')

My run looks like this:

  1. xxx is printed
    [After 1 second]
  2. ZZ is printed
    [After 1 second]
  3. The line is deleted
    [After 1 second]
  4. === is printed and the program terminates

This happens both in the debug and the run console when running this script.

like image 255
TomM Avatar asked Jan 12 '16 18:01

TomM


People also ask

Does Python strip remove carriage return?

Using strip() method to remove the newline character from a string. The strip() method will remove both trailing and leading newlines from the string. It also removes any whitespaces on both sides of a string.

How do you escape a carriage return?

Carriage return means to return to the beginning of the current line without advancing downward. The name comes from a printer's carriage, as monitors were rare when the name was coined. This is commonly escaped as "\r", abbreviated CR, and has ASCII value 13 or 0xD.

What is console in Pycharm?

The console appears as a tool window every time you choose the corresponding command on the Tools menu. You can assign a shortcut to open Python console: press Ctrl+Alt+S , navigate to Keymap, specify a shortcut for Main menu | Tools | Python or Debug Console.


2 Answers

The answer is actually in your post. As you said, the carriage return deletes the whole line. To avoid the issue, print the carriage return only when you print the new line, like so:

Print each line with the carriage return at the start, and without the default end='\n'. Didn't need the flush, though I didn't do much testing.

print('\rxxx', end='')
# sys.stdout.flush()
time.sleep(1)

Continue like this...

print('\rZZ', end='')
time.sleep(1)

print('\ryyy', end='')
time.sleep(1)

To keep the last printout, keep the default end.

print('\r===')
like image 128
Bushman Avatar answered Oct 01 '22 21:10

Bushman


The bug is still active and it was reported here. For now if you Use the Run > Configuration > "Emulate Terminal in Output Console" the carriage return will function as intended.

like image 27
Spasnof Avatar answered Oct 01 '22 20:10

Spasnof