remove last STDOUT line in Python

后端 未结 5 745
温柔的废话
温柔的废话 2020-11-28 11:17

I am trying to figure out how to suppress the display of user input on stdout.

raw_input() followed by any print statement preserves what the user typed

5条回答
  •  遥遥无期
    2020-11-28 11:38

    The following code, based on the Python docs, uses the termios module and seems to do what you want (although it is not as compact as VT100 control codes):

    def getpass(prompt="Password: "):
        import termios, sys
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        new = termios.tcgetattr(fd)
        new[3] = new[3] & ~termios.ECHO
        try:
            termios.tcsetattr(fd, termios.TCSADRAIN, new)
            passwd = raw_input(prompt)
            print '\r          \r',
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old)
        return passwd
    
    p = getpass()
    

    There are two tricky lines: one disables the echo, the other one erases your password prompt remaining at the first position of the line.

提交回复
热议问题