Abhinath Kumar Abhinath Kumar - 24 days ago 9
Python Question

Masking keyboard input with a character - Python version 3.0

Look, no one has been answering my question properly and are duplicating my previous question as I was not clear on my previous question

I want to mask my keyboard input with a character such as an asterisk on Python version 3 and above on a windows operating system,

I have this so far,

import getpass

pswd = getpass.getpass('Password:')


I can hide the password input, but I am not able to display a character for each individual letter

I tried using msvcrt module, but an error saying no module name 'msvcrt' keeps popping pop, probably because i have Python version 3 and above. I also don't want to use tKinter either.

If anyone can help by adding a few lines of code to fix this would be a great help, as it is for my computer science coursework

Answer

I think I have just what you need. Password is set to variable name 'psw'. This only seems to work in cmd though.

import msvcrt
import time
import sys
import os

def getPASS():
    print("Input password")
    list1 = []
    while True:
        char = msvcrt.getch()
        char =str(char)
        char = char[2:-1]
        if char == "\\n'" or char == "\\r":
            break
    elif char == "\\x08":
        del list1[-1]
        os.system("cls")
        print("Input password:")
        sys.stdout.write("*" * len(list1))
        sys.stdout.flush()
        continue
    else:
        list1.append(char)
        sys.stdout.write("*")
        sys.stdout.flush()
print("\n")
psw = "".join(list1)
print(psw)
invalid = ' ,:;/?"\}]{[-=+!@#$%^&*()|'
for x in psw:
    if x in invalid:
        print("Character %r is not allowed in password" % x)
        getPASS()
    else:
        pass

getPASS()

Please give any improvements, Dan

Comments