'\\b' doesn't print backspace in PyCha

2020-02-14 02:31发布

问题:

I am trying to update the last line in PyCharm's console. Say, I print a and then I want to change it to c. However, I encounter the following problem. When I run:

print 'a\bc'

it prints

a c

while the desired output (which is also what I see in the Windows console) is:

c

Is there a way to move the cursor back in PyCharm's console? or maybe delete the whole line?

回答1:

It's a known bug: http://youtrack.jetbrains.com/issue/PY-11300

If you care about this, please get an account on the bug tracker and upload the bug to give it more attention.



回答2:

This is not a bug, this is a limitation of the interactive console found both in PyCharm, and in the IDLE shell.

When using the command prompt of windows, or a linux shell - the \b character is interpreted as a backspace and implemented as it is being parsed - However, in the interactive console of PyCharm and IDLE the \b character and many others are disabled, and instead you simply get the ASCII representation of the character (a white space in most cases).



回答3:

The \r works. I know this is ASCII Carriage Return, but i use this as a workaround

print("\ra")
print("\rc")

will yield in c in the console

By the way, backspace is a ASCII Character



回答4:

I just ran into the same issue in PyCharm (2019.1) and stumbled on this post. It turns out that you can use the \b character if you use the sys.stdout.write function instead of print. I wasn't able to get any of the above examples working within PyCharm using the print function.

Here's how I update the last line of text in my code assuming I don't need more than 100 characters:

# Initialize output line with spaces
sys.stdout.write(' ' * 100)

# Update line in a loop
for k in range(10)
    # Generate new line of text
    cur_line = 'foo %i' % k

    # Remove last 100 characters, write new line and pad with spaces
    sys.stdout.write('\b' * 100)
    sys.stdout.write(cur_line + ' '*(100 - len(cur_line)))

    # ... do other stuff in loop

This should generate "foo 1", then replaced with "foo 2", "foo 3", etc. all on the same line and overwriting the previous output for each string output. I'm using spaces to pad everything because different programs implement the backspace character differently, where sometimes it removes the character, and other times it only moves the cursor backwards and thus still requires new text to overwrite.

I've got to credit the Keras library for this solution, which correctly updates the console output (including PyCharm) during learning. I found that they were using the sys.stdout.write function in their progress bar update code.