User reset

I am trying to create a program that accepts user input, but instead of displaying the actual input, I would like to replace the input with

I tried using this code, but I keep getting the error below, I would appreciate any guidance or help.

import msvcrt import sys def userinput(prompt='>'): write = sys.stdout.write for x in prompt: msvcrt.putch(x) entry = "" while 1: x = msvcrt.getch() print(repr(x)) if x == '\r' or x == '\n': break if x == '\b': entry = entry[:-1] else: write('*') entry = entry + x return entry userEntry = userinput() 

Error:

 Traceback (most recent call last): File "C:\Users\Mehdi\Documents\Teaching\KS5\AS CS\getPass.py", line 24, in <module> userEntry = userinput() File "C:\Users\Mehdi\Documents\Teaching\KS5\AS CS\getPass.py", line 9, in userinput msvcrt.putch(x) TypeError: putch() argument must be a byte string of length 1, not str 
+5
source share
1 answer

According to the error received, putch receives a byte, not a string, so use

 for x in prompt: msvcrt.putch(x.encode()[:1]) 

( [:1] usually not required, just to make sure that the byte array is 1 as needed)


A more common practice than using streams would be to use msvcrt.getch and a loop until you get a new line when printing a line of user input length full * each time and printing one line by returning the carriage to the end print function:

 import msvcrt def getch(): return chr(msvcrt.getch()[0]) def hidden_input (input_message = 'enter input:'): user_input = '' new_ch = '' while new_ch != '\r': print(input_message, '*' * len(user_input), ' ' * 20, end = '\r') user_input = user_input[:-1] if new_ch == '\b' else user_input + new_ch new_ch = getch() return user_input hidden_input() 
-1
source

Source: https://habr.com/ru/post/1259930/


All Articles