What is the use of '\b' (backspace)

前端 未结 4 1744
我寻月下人不归
我寻月下人不归 2021-01-13 16:30

I\'m taking a Python class right now, and I just learned about the backspace character. Like newline (\\n), backspace is a special character with ASCII code 8. My teacher c

4条回答
  •  醉酒成梦
    2021-01-13 16:52

    Maybe it helps to first understand what is happening there:

    print() is writing to the standard output and it is writing everything there including the w and the backspace.

    Now something has to display it. Most likely a terminal emulator.

    What theoretically would happen is that the w was displayed and then deleted, but it was not flushed and was to fast for it to actually happen.

    So real-life applications will almost always use \b at the beginning of the printed text.

    I wrote a short example that will have a little spinner on a progress indicator. The example print "-" followed by "\b\\" (deleting the - and replacing it with \) followed by "\b|" (deleting the \ and replacing it with |) and so on.

    That way - \ | / - \ | / looks like an animated rotating line.

    #!/usr/bin/env python3
    import time
    
    spinner="\\|/-"
    print ("----------\r", end='', flush=True)
    for pos in range(10):
        print ("-", end='', flush=True)
        for spin in range(25):
            #here should be a break as soon as some task proceeded further
            time.sleep(0.1)
            print ("\b" + spinner[spin % 4], end='', flush=True)
        print ("\b*", end='', flush=True)
    print ()
    

    P.S.: A lot of existing programs use control characters like \b \r \033 to display a status line. Most popular is probably wget. I have also seen such output by at least one python script (although I cant remember which one any more)

提交回复
热议问题