'\b' doesn't print backspace in PyCharm console

前端 未结 4 618
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 19:05

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 pro

4条回答
  •  -上瘾入骨i
    2020-12-20 19:15

    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.

提交回复
热议问题