def getpass(prompt = 'Password: '******'utf8')) while True: new_char = msvcrt.getch() if new_char in b'\r\n': break elif new_char == b'\0x3': #ctrl + c raise KeyboardInterrupt elif new_char == b'\b': if chars and count >= 0: count -= 1 chars = chars[:-1] msvcrt.putch(b'\b') msvcrt.putch(b'\x20')#space msvcrt.putch(b'\b') else: if count < 0: count = 0 count += 1 chars.append(new_char.decode('utf8')) msvcrt.putch(b'*') return ''.join(chars)
def getPass(): import msvcrt print('请输入数据库帐号密码:', end='', flush=True) li = [] while True: ch = msvcrt.getch() # 回车 if ch == b'\r': msvcrt.putch(b'\n') return b''.join(li).decode() break # 退格 elif ch == b'\x08': if li: li.pop() msvcrt.putch(b'\b') msvcrt.putch(b' ') msvcrt.putch(b'\b') # ESC elif ch == b'\x1b': break else: li.append(ch) msvcrt.putch(b'*') return b''.join(li).decode()
def getreply(): """ 读取交互式用户的回复健,即使stdin重定向到某个文件或者管道 """ if sys.stdin.isatty(): return input('--more--') else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key elif sys.platform == 'linux': import tty import termios print('--more[y]--') 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 else: assert False, 'platform not supported'
def getResponse(self): try: if sys.stdin.isatty(): return raw_input(">") else: if sys.platform[:3] == "win": import msvcrt msvcrt.putch(">") key = msvcrt.getche() msvcrt.putch("\n") return key elif sys.platform[:5] == "linux": print ">" console = open("/dev/tty") line = console.readline()[:-1] return line else: print "[pause]" import time time.sleep(5) return "y" except: return "done"
def get_command(): """Uses the msvcrt module to get key codes from buttons pressed to navigate through the game. The arrows, enter, tab, Page Down, and escape keys are used so far.""" cmd = "" while 1: key = ord(getch()) if key == 224: key = ord(getch()) cmd = arrow_keys.get(key, "") return cmd elif key == 13: putch("\n") break elif key == 8: cmd = cmd[:-1] putch(chr(8)) putch(" ") putch(chr(8)) elif key == 27: cmd = 'q' return cmd elif key == 9: cmd = 'tab' return cmd else: putch(chr(key)) cmd += chr(key) return cmd
def getpwd(self, msg=""): print(msg, end="") sys.stdout.flush() pwd = [] while True: ch = msvcrt.getch() if ch == b'\r': msvcrt.putch(b'\n') return b"".join(pwd).decode() break elif ch == b'\x08': if pwd: pwd.pop() msvcrt.putch(b'\b') msvcrt.putch(b' ') msvcrt.putch(b'\b') elif ch == b'\x03': raise KeyboardInterrupt() elif ch == b'\x1b': break else: pwd.append(ch) msvcrt.putch(b'*')
def adinput(prompt, default=None): putstr(prompt) if default is None: data = [] else: data = list(default) putstr(data) while True: c = getch() if c in '\r\n': break elif c == '\003': # Ctrl-C putstr('\r\n') raise KeyboardInterrupt elif c == '\b': # Backspace if data: putstr('\b \b') # Backspace and wipe the character cell data.pop() elif c in '\0\xe0': # Special keys getch() else: putch(c) data.append(c) putstr('\r\n') return ''.join(data)
def creat_pw(self, markedWords): '''实现控制台密码星号输入,借鉴网上代码''' print(markedWords, end='', flush=True) li = [] while 1: ch = msvcrt.getch() # 回车 if ch == b'\r': msvcrt.putch(b'\n') # print('输入的密码是:%s' % b''.join(li).decode()) return b''.join(li).decode() # 退格 elif ch == b'\x08': if li: li.pop() msvcrt.putch(b'\b') msvcrt.putch(b' ') msvcrt.putch(b'\b') # Esc elif ch == b'\x1b': break else: li.append(ch) msvcrt.putch(b'*') return ''.join(li).strip()
def interruptMeasurement( pressedKey_bool): #if a key is being hit in the process if pressedKey_bool == True: #winsound.PlaySound('SystemQuestion',winsound.SND_ALIAS) #play some sound msvcrt.putch( msvcrt.getch()) #print the character to get it out of the buffer while 1: check = str( raw_input( "\nType \"REPEAT\" to terminate the current iteration.\nTzpe \"CONTINUE\" to proceed with the current iteration: " )) if check == "REPEAT": #ask for repeating the current iteration or continueing pyautogui.doubleClick(pos_stopbutton, button="left") print("[system]\tMeasurement \"" + str(setname) + "\" terminated\n") return True elif check == "CONTINUE": print(Fore.YELLOW + Style.NORMAL + "\nPlease return to the TeraView window immediately!") print(Style.RESET_ALL) time.sleep(3) print( "\n[system]\tContinuing measurement \"" + str(setname) + "\".\n\t\tPress any key to interrupt the current measurement" ) LS331.query('ALARM B,0') break
def get_pass(): """ Gets user password without showing the entered characters. Shows ***** instead. """ # Comma after print to avoid new line. print("Password: "), password = '' while 1: # Get input, 1 character at a time. x = msvcrt.getch() # If input is enter. if x == '\r' or x == '\n': break # If input is backspace. elif x == '\x08': # Only delete from the password string # not the prompt message. if len(password) > 0: password = password[:-1] sys.stdout.write('\x08 \x08') else: sys.stdout.write('*') password = password + x msvcrt.putch('\n') return password
def input_passwd_for_win(prompt_message="input password:"): print(prompt_message, end='', flush=True) list_ch = [] import msvcrt while 1: ch = msvcrt.getch() # 回车 if ch == b'\r': msvcrt.putch(b'\n') # print('输入的密码是:%s' % b''.join(li).decode()) break # 退格 elif ch == b'\x08': if list_ch: list_ch.pop() msvcrt.putch(b'\b') msvcrt.putch(b' ') msvcrt.putch(b'\b') # Esc elif ch == b'\x1b': break else: list_ch.append(ch) msvcrt.putch(b'*') return list_ch
def input_windows(self): """ Ensures that the I/O is non-blocking for windows.""" userstring = [] while self.alive: print("> " + "".join(userstring), end="", flush=True) t0 = time.time() while time.time() - t0 < 1: if msvcrt.kbhit(): character = msvcrt.getch() char_decode = character.decode("utf-8") if char_decode == "\b": if len(userstring) > 0: sys.stdout.write("\b") sys.stdout.write(" ") sys.stdout.flush() del userstring[-1] msvcrt.putch(character) continue elif char_decode == "\r": print("\n") return userstring msvcrt.putch(character) userstring.append(char_decode) time.sleep(0.1) sys.stdout.write("\r")
def getpwd(prompt='password:'******'utf8')) while True: new_char = msvcrt.getch() if new_char in b'\r\n': break elif new_char == b'\0x3': raise KeyboardInterrupt elif new_char == b'\b': if chars and count >= 0: count -= 1 chars = chars[:-1] msvcrt.putch(b'\b') msvcrt.putch(b'\x20') msvcrt.putch(b'\b') else: if count < 0: count = 0 count += 1 chars.append(new_char.decode('utf8')) msvcrt.putch(b'*') return ''.join(chars)
def _getpass(prompt='Password:'******'\r\n': break elif new_char == '\0x3': #ctrl + c raise KeyboardInterrupt elif new_char == '\b': if chars and count >= 0: count -= 1 chars = chars[:-1] msvcrt.putch('\b') msvcrt.putch('\x20')#space msvcrt.putch('\b') else: if count < 0: count = 0 count += 1 chars.append(new_char) msvcrt.putch('*') # 在输入之后回车,防止下一个输出直接接在在密码后面 print "" return ''.join(chars)
def run(self): """ """ global _Server_Queue while True: # What would cause this to stop? Only the program ending. line = "" while 1: char = msvcrt.getche() if char == "\r": # enter break elif char == "\x08": # backspace # Remove a character from the screen msvcrt.putch(" ") msvcrt.putch(char) # Remove a character from the string line = line[:-1] elif char in string.printable: line += char time.sleep(0.01) try: _Server_Queue.put(line) if line != "": _Logger.debug("Input from server console: %s" % line) except: pass
def getreply(): """ Читает клавишу нажатую пользователем даже если stdin перенаправлен в файл или канал """ # если stdin связан с консолью if sys.stdin.isatty(): # читать ответ из stdin return input('?') # иначе - если stdin был перенаправлен # его нельзя использовать для чтения пользователя # обрабатываем в зависимости от платформы else: # Windows if sys.platform[:3] == 'win': import msvcrt # используем инструменты консоли windows msvcrt.putch(b'?') # приглашение к вводу '?' key = msvcrt.getche() # getche() - не выводит символ для нажатой msvcrt.putch(b'\n') # клавиши return key # Linux elif sys.platform[:5] == 'linux': # в линуксе для чтения ввода с клавиатуры # достаточно подключиться к устройству /dev/tty print('?', end='', flush=True) tty = open('/dev/tty').readline()[:-1] return tty.encode() # Текущая платформа не поддерживается else: assert False, 'platform not supported'
def putch(ch): if type(ch) is int: ch = chr(ch).encode(encoding = 'UTF-8') elif type(ch) is bytes: pass else: ch = str(ch).encode(encoding = 'UTF-8') msvcrt.putch(ch)
def putchxy(x, y, ch): """ Puts a char at the specified position. The cursor position is not affected. """ prevCurPos = getcurpos() setcurpos(x, y) msvcrt.putch(ch) setcurpos(prevCurPos.x, prevCurPos.y)
def getReply(): if sys.stdin.isatty(): return input("?") if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key else: assert False, 'platform not supported'
def getreply(): if sys.stdin.isatty(): return sys.stdin.read(1) else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() return key else: return open('/dev/tty').readline()[:-1]
def readch(echo=True): "Get a single character on Windows." while msvcrt.kbhit(): # clear out keyboard buffer ch = msvcrt.getch() if ch in '\x00\xe0': # arrow or function key prefix? ch = msvcrt.getch() # second call returns the actual key code ch = msvcrt.getch() if ch in '\x00\xe0': # arrow or function key prefix? ch = msvcrt.getch() # second call returns the actual key code if echo: msvcrt.putch(ch) return ch
def getreply(): if sys.stdin.isatty(): #如果sys.stdin 是控制台 return input('?') else: if sys.platform[:3] == "win": import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() #使用windows控制台工具 msvcrt.putch(b'\n') #getch()方法不能回应键 return key else: assert False,'platform not supported'
def getreply(): if sys.stdin.isatty(): # 如果 stdin 是控制台,从stdin读取数据 return input('?:') else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch('?') key = msvcrt.getche() # 获取键盘输入 msvcrt.putch('\n') return key else: assert False, 'platform not supported'
def getreply(): if sys.stdin.isatty(): return input('?') else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key else: return open('/dev/tty').readline()[:-1]
def readChar(echo=True): "Get a single character on Windows." while msvcrt.kbhit(): msvcrt.getch() ch = msvcrt.getch() while ch in b'\x00\xe0': msvcrt.getch() ch = msvcrt.getch() if echo: msvcrt.putch(ch) #return ch.decode() return ch.decode()
def getreply(): if sys.stdin.isatty(): return input('?') else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key else: assert False, 'platform not suppordted'
def getreply(): if sys.stdin.isatty(): return raw_input("?") else: if sys.platform[:3] == "lin": import msvcrt msvcrt.putch(b"?") key = msvcrt.getche() msvcrt.putch(b"\n") return key else: assert False, "platform not supported"
def getreply(): # 读取交互式用户的回复键,即使stdin重定向到某个文件或者管道 if sys.stdin.isatty(): #如果stdin是控制台 return input('?') #从stdin读取回复行数据 else: if sys.platform[:3] == 'win': #如果stdin重定向 import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() #使用windows控制台工具 msvcrt.putch(b'\n') #getch()方法不能回应键 return key else: assert False, 'platform not supported'
def passinput(): print "\t\tEnter Password:", ch='' i=0 pas = '' pasw=[] while True : ch=msvcrt.getch() if (ord(ch)==12 or ord(ch)==13): break elif (ord(ch) == 8): if(i>0): msvcrt.putch('\b') msvcrt.putch(' ') msvcrt.putch('\b') i-=1 pas=pas[:i] elif (ord(ch) in range(37,40)): pass #elif (ord(ch) in range(32,126)): elif (ord(ch)>=65 and ord(ch)<=90) or (ord(ch)>=97 and ord(ch)<=122) or (ord(ch)>=48 and ord(ch)<=57): i+=1 pas=pas+ch msvcrt.putch ('*') else: pas=pas[:i] return pas
def readInput(caption, default, timeout: int = 5): start_time = time.time() print('{}({})\r\n>'.format(caption, default), end="") input = '' while True: if msvcrt.kbhit(): chr = msvcrt.getwche() if ord(chr) == 13: # enter_key break elif ord(chr) == 27: break elif ord(chr) == 8: if input != "": input = input[:-1] msvcrt.putch(b" ") msvcrt.putch(b" ") msvcrt.putch(b"\b") msvcrt.putch(b"\b") if len(input) == 0: start_time = time.time() elif 32 > ord(chr) or 255 > ord(chr) > 126: # space_char continue else: input += chr if len(input) == 0 and (time.time() - start_time) > timeout: break if len(input) > 0: print() return input else: print("使用默认值") return default
def pwd_input(msg): print msg, import msvcrt chars = [] while True: try: new_char = msvcrt.getch().decode(encoding="utf-8") except: return input("你很可能不是在 cmd 命令行下运行,密码输入将不能隐藏:") if new_char in '\r\n': # 如果是换行,则输入结束 break elif new_char == '\b': # 如果是退格,则删除密码末尾一位并且删除一个星号 if chars is not None: del chars[-1] msvcrt.putch('\b'.encode(encoding='utf-8')) # 光标回退一格 msvcrt.putch(' '.encode(encoding='utf-8')) # 输出一个空格覆盖原来的星号 msvcrt.putch('\b'.encode(encoding='utf-8')) # 光标回退一格准备接受新的输入 else: chars.append(new_char) msvcrt.putch('*'.encode(encoding='utf-8')) # 显示为星号 print return ''.join(chars)
def pwd_input(text): """ 输入信息加密 """ print(text, end='', flush=True) chars = [] while True: try: newChar = msvcrt.getch().decode(encoding="utf-8") except: return input("你很可能不是在cmd命令行下运行,密码输入将不能隐藏:") # 换行 -- 输入结束 if newChar in '\r\n': break # 如果是退格,则删除密码末尾一位并且删除一个星号 elif newChar == '\b': # 如果是退格,则删除密码末尾一位并且删除一个星号 if chars: del chars[-1] # 光标回退一格 msvcrt.putch('\b'.encode(encoding='utf-8')) # 输出一个空格覆盖原来的星号 msvcrt.putch(' '.encode(encoding='utf-8')) # 光标回退一格准备接受新的输入 msvcrt.putch('\b'.encode(encoding='utf-8')) else: chars.append(newChar) # 命令行中显示为星号 msvcrt.putch('*'.encode(encoding='utf-8')) # 返回真实信息 return (''.join(chars))
def getreply(): ''' 读取交互式用户的回复键,即使stdin重定向到某个文件或者管道 ''' if sys.stdin.isatty(): return input('?') # 如果stdin 是控制台 从stdin 读取回复行数据 else : if sys.platform[:3] == 'win': # 如果stdin 重定向,不能用于询问用户 import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() # 使用windows 控制台工具 getch()方法不能回应键 return key else: assert False,'platform not supported'
def getreply(): ''' 读取交互式用户的回复键,即使stdin重定向到某个文件或者管道 ''' if sys.stdin.isatty(): return input('?') else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key else: assert False, 'Platform not supported'
def getreply(): """ 读取交互用户的回复键,即使stdin重定向到某个文件或者管道 """ if sys.stdin.isatty(): # 如果stdin是控制台 return bytes(input('?'), 'utf8') # 从stdin读取回复行数据 else: if sys.platform[:3] == 'win': # 如果stdin重定向 import msvcrt # 不能用于询问用户 msvcrt.putch(b'?') key = msvcrt.getche() # 使用windows控制台工具 msvcrt.putch(b'\n') # getch()方法不能回应键 return key else: assert False, 'platform not supported'
def getreply(): """ read a reply key from an interactive user even if stdin redirected to a file or pipe """ if sys.stdin.isatty(): return input('?') else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key else: assert False, 'platform not supported'
def getreply(): ''' читает клавишу, нажатую пользователем, даже если stdin перенаправлен в файл или канал ''' if sys.stdin.isatty(): return input('?') else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key else: assert False, 'platform not supported'
def getreply(): """ read a reply key from an interactive user even if stdin redirected to a file or pipe """ if sys.stdin.isatty(): # if stdin is console return input('?') # read reply line from stdin else: if sys.platform[:3] == 'win': # if stdin was redirected import msvcrt # can't use to ask a user msvcrt.putch(b'?') key = msvcrt.getche() # use windows console tools msvcrt.putch(b'\n') # getch() does not echo key return key else: assert False, 'platform not supported'
def getreply(): """ 读取交互式用户的回复键,即使stdin重定向到某个文件或者管道 """ if sys.stdin.isatty(): # 如果stdin是控制台 return input('?') # 从stdin读取回复行数据 else: if sys.platform[:3] == 'win': # 如果stdin重定向 import msvcrt # 不能用于询问用户 msvcrt.putch(b'?') key = msvcrt.getche() # 使用windows控制台工具 msvcrt.putch(b'\n') # getch()方法不能回应键 return key else: # linux?: open('/dev/tty').readline().[:-1] assert False, 'platform not supported'
def getreply(): """ читает клавиишу, нажатую пользователем, даже если stdin перенаправлен в файл или канал """ if sys.stdin.isatty(): # если stdin связан с консолью return input('?') # читать ответ stdin else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getch() msvcrt.putch(b'\n') return key else: assert False, 'platform not suported'
def getreply(): """ читает клавишу, нажатую пользователем, даже если stdin перенаправлен в файл или канал """ if sys.stdin.isatty(): # если stdin связан с консолью, return input('?') # читать ответ из stdin else: if sys.platform[:3] == 'win': # если stdin был перенаправлен, import msvcrt # его нельзя использовать для чтения msvcrt.putch(b'?') # ответа пользователя key = msvcrt.getche() # использовать инструмент консоли msvcrt.putch(b'\n') # getch(), которая не выводит символ return key # для нажатой клавиши else: assert False, 'platform not supported'
def getreply(): """ read a reply key from an interactive user even if stdin redirected to a file or pipe """ if sys.stdin.isatty(): #if stdin is concole return input('?') #read reply else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch(b'?') key = msvcrt.getche() msvcrt.putch(b'\n') return key else: assert False, 'platform not supported'
def do_stop(self, line): '''stop Shuts down the server gently...ish.''' global RUNNING RUNNING=False #In order to finalize this, we need to wake up all #threads. Main is awake on a one-second loop, the #server does acquiry every 5 seconds, and the client #manager every fraction of a second. Our UIthread will #respond to a character, so lets put one on there: if curses: curses.ungetch('\x00') elif msvcrt: msvcrt.putch('\x00') #else, panic. #after that's done, all the threads should realize that #it's time to pack up. print 'This will take up to 5 seconds...'
def getreply(): """ read a reply key from an interactive user even if stdin redirected to a file or pipe """ if sys.stdin.isatty(): # if stdin is console return input("More? y/Y") # read reply line from stdin else: if sys.platform[:3] == 'win': # if stdin was redirected import msvcrt # can't use to ask a user msvcrt.putch(b'?') key = msvcrt.getche() # use windows console tools msvcrt.putch(b'\n') # getch() does not echo key return key elif sys.platform == 'darwin': os.system("printf 'More? '") key = open('/dev/tty').readline()[:-1] os.system("printf '\n'") return key else: assert False, 'platform not supported'
def run(self): """ """ global _CMD_Queue global _Quit _Quit_Lock.acquire() done = _Quit _Quit_Lock.release() logger.write_line("Beginning Read Line Thread loop") while not done: line = "" while 1: char = msvcrt.getche() if char == "\r": # enter break elif char == "\x08": # backspace # Remove a character from the screen msvcrt.putch(" ") msvcrt.putch(char) # Remove a character from the string line = line[:-1] elif char in string.printable: line += char time.sleep(0.01) try: _CMD_Queue.put(line) if line != "": logger.write_line("Input from user: %s" % line) except: pass _Quit_Lock.acquire() done = _Quit _Quit_Lock.release()
def ReadLine(label, defaultValue = "", password = False): """Read a line of input from stdin and return it. If nothing is read, the default value is returned. Note that if stdin in not a TTY, the label will not be displayed.""" if sys.stdin.isatty(): if defaultValue: label += " [%s]" % defaultValue label += ": " if password: result = getpass.getpass(label) else: if sys.platform == "win32": import msvcrt for c in label: msvcrt.putch(c) result = sys.stdin.readline().strip() else: result = raw_input(label).strip() else: result = raw_input().strip() if not result: return defaultValue return result
def getreply(): ''' read a reply from a user ,even if stdin redirected to a file or pipe ''' if sys.stdin.isatty(): return raw_input('?') else: if sys.platform[:3] == 'win': import msvcrt msvcrt.putch('?') key = msvcrt.getche() msvcrt.putch('\n') return key elif sys.platform[:5] == 'linux': print '?', console = open('/dev/tty') line = console.readline()[:-1] return line else: print '[pause]' import time time.sleep(5) return 'y'
def getreply(): """ read a reply key from an interactive user even if stdin redirected to a file or pipe """ if sys.stdin.isatty(): # if stdin is console return raw_input('?') # read reply line from stdin else: if sys.platform[:3] == 'win': # if stdin was redirected import msvcrt # can't use to ask a user msvcrt.putch('?') # use windows console tools key = msvcrt.getche() # getch( ) does not echo key msvcrt.putch('\n') return key elif sys.platform[:5] == 'linux': # use linux console device print '?' # strip eoln at line end console = open('/dev/tty') line = console.readline()[:-1] return line else: print '[pause]' # else just pause--improve me import time # see also modules curses, tty time.sleep(5) # or copy to temp file, rerun return 'y' # or GUI pop up, tk key bind
def pwd_input(): chars = [] while True: try: newChar = msvcrt.getch().decode(encoding="utf-8") except: return input("你很可能不是在cmd命令行下运行,密码输入将不能隐藏:") if newChar in '\r\n': break elif newChar == '\b': if chars: del chars[-1] msvcrt.putch('\b'.encode(encoding='utf-8')) msvcrt.putch( ' '.encode(encoding='utf-8')) msvcrt.putch('\b'.encode(encoding='utf-8')) else: chars.append(newChar) msvcrt.putch('*'.encode(encoding='utf-8')) return (''.join(chars) )
def pwd_input(): chars = [] while True: try: newChar = msvcrt.getch().decode(encoding="utf-8") except: return input("【温馨提醒:当前未在cmd命令行下运行,密码输入无法隐藏】:\n") if newChar in "\r\n": break elif newChar == "\b": if chars: del chars[-1] msvcrt.putch("\b".encode(encoding="utf-8")) msvcrt.putch(" ".encode(encoding="utf-8")) msvcrt.putch("\b".encode(encoding="utf-8")) else: chars.append(newChar) msvcrt.putch("*".encode(encoding="utf-8")) return "".join(chars)
def pwd_input(): chars = [] while True: try: newChar = msvcrt.getch().decode(encoding="utf-8") except: return input("你很可能不是在cmd命令行下运行,密码输入将不能隐藏:") if newChar in "\r\n": # 如果是换行,则输入结束 break elif newChar == "\b": # 如果是退格,则删除密码末尾一位并且删除一个星号 if chars: del chars[-1] msvcrt.putch("\b".encode(encoding="utf-8")) # 光标回退一格 msvcrt.putch(" ".encode(encoding="utf-8")) # 输出一个空格覆盖原来的星号 msvcrt.putch("\b".encode(encoding="utf-8")) # 光标回退一格准备接受新的输入 else: chars.append(newChar) msvcrt.putch("*".encode(encoding="utf-8")) # 显示为星号 return "".join(chars)
def run(self): line = "" while 1: c = getch() if ord(c) == SPECIAL_KEY: c = getch() self.outQ.put((SPECIAL_KEY,ord(c))) elif ord(c) == ESCAPE_KEY: self.outQ.put(False) break elif ord(c) == ENTER_KEY: self.outQ.put(line) line = "" elif ord(c) == BACKSPACE_KEY: line = line[:-1] putch(c) putch(" ") putch(c) else: line += c putch(c)
def pwd_input(): print '请输入密码:', chars = [] while True: try: newChar = msvcrt.getch().decode(encoding="utf-8") except: return raw_input("你很可能不是在cmd命令行下运行,密码输入将不能隐藏:") if newChar in '\r\n': # 如果是换行,则输入结束 break elif newChar == '\b': # 如果是退格,则删除密码末尾一位并且删除一个星号 if chars: del chars[-1] msvcrt.putch('\b'.encode(encoding='utf-8')) # 光标回退一格 msvcrt.putch(' '.encode(encoding='utf-8')) # 输出一个空格覆盖原来的星号 msvcrt.putch('\b'.encode(encoding='utf-8')) # 光标回退一格准备接受新的输入 else: chars.append(newChar) msvcrt.putch('*'.encode(encoding='utf-8')) # 显示为星号 return (''.join(chars) ) return chars
def win_getpass(prompt='Password: '******'\r' or c == '\n': break if c == '\003': raise KeyboardInterrupt if c == '\b': pw = pw[:-1] else: pw = pw + c msvcrt.putch('\r') msvcrt.putch('\n') return pw
def getpassword(prompt = ""): password = "" put = sys.stdout.write for i in prompt: visualc.putch(i) while True: char = visualc.getch() if char == '\n' or char == '\r': #Salto de linea break if char == '\b': #Retroceso put("\x08 \x08") password = password[:-1] else: put('*') password = password + char visualc.putch('\r') visualc.putch('\n') return password #print getpassword() #raw_input()
def win_getpass(prompt="Password: "******"""Prompt for password with echo off, using Windows getch().""" if sys.stdin is not sys.__stdin__: return fallback_getpass(prompt, stream) import msvcrt for c in prompt: msvcrt.putch(c) pw = "" while 1: c = msvcrt.getch() if c == "\r" or c == "\n": break if c == "\003": raise KeyboardInterrupt if c == "\b": pw = pw[:-1] else: pw = pw + c msvcrt.putch("\r") msvcrt.putch("\n") return pw
def win_getpass(prompt = 'Password: '******'' while 1: c = msvcrt.getch() if c == '\r' or c == '\n': break if c == '\x03': raise KeyboardInterrupt if c == '\x08': pw = pw[:-1] else: pw = pw + c msvcrt.putch('\r') msvcrt.putch('\n') return pw