Python Forum
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
**** PassWord
#5
getpass is a module in the standard lib, it is 100% python code.  Here's the source: https://github.com/python/cpython/blob/3...getpass.py

It uses getch, which gets a single character from input instead of a whole line.  In order to do so without also echoing what you type, it uses a different method depending on your operating system.  So, I copied a lot of that, and changed it a bit to ALSO echo out an asterisk while waiting for input.

import sys

def _find_getch():
    try:
        import termios
    except ImportError:
        # Non-POSIX. Return msvcrt's (Windows') getch.
        import msvcrt
        return msvcrt.getch

    # POSIX system. Create and return a getch that manipulates the tty.
    import tty
    def _getch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

    return _getch

getch = _find_getch()

pword = ''
ch = 'spam'
# keep looping until "enter" is hit
while ch not in '\r\n':
    ch = getch().decode()
    pword += ch

    print('*', end='')
    # we need to flush, or else the asterisks won't appear
    # until after the password is finished getting entered
    sys.stdout.flush()
# add a newline after the asterisks
print()

# prove that we actually got something
print(pword)
Output:
D:\Projects\playground>python pword.py ********************************* spam, spam, spam, spam, and eggs
Reply


Messages In This Thread
**** PassWord - by kadoushka - Mar-19-2017, 09:10 AM
RE: **** PassWord - by sparkz_alot - Mar-19-2017, 12:40 PM
RE: **** PassWord - by Larz60+ - Mar-19-2017, 04:42 PM
RE: **** PassWord - by zivoni - Mar-19-2017, 05:19 PM
RE: **** PassWord - by nilamo - Mar-19-2017, 05:26 PM
RE: **** PassWord - by kadoushka - Mar-22-2017, 01:54 PM
RE: **** PassWord - by nilamo - Mar-22-2017, 02:23 PM
RE: **** PassWord - by wavic - Apr-03-2017, 02:13 AM
RE: **** PassWord - by metulburr - Apr-03-2017, 02:26 AM
RE: **** PassWord - by wavic - Apr-03-2017, 02:30 AM
RE: **** PassWord - by zivoni - Apr-03-2017, 06:48 AM
RE: **** PassWord - by ashishskyblue - Jan-12-2020, 04:49 AM
RE: **** PassWord - by rmspacedashrf - Jan-12-2020, 07:31 AM
RE: **** PassWord - by Gribouillis - Jan-12-2020, 07:44 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020