2014-12-24 29 views
4

我試圖用星號掩蓋用戶輸入IDLE的內容,因此他們周圍的人看不到他們正在輸入/輸入的內容。我使用基本的原始輸入來收集他們鍵入的內容。之後用戶鍵入密碼在python中用星號屏蔽用戶輸入

key = raw_input('Password :: ') 

理想IDLE提示:

Password :: ********** 
+0

你將不得不做一些自定義的標準輸出重定向用星號來掩蓋,但還有一個更簡單的方式來獲得密碼http://stackoverflow.com/a/1761753/1268926 – Kedar

回答

2

根據不同的操作系統,你是如何從用戶的輸入,以及如何檢查回車會得到不同的單個字符上。

看到這個職位:Python read a single character from the user

在OSX,例如,你可以使這樣的事情:

import sys, tty, termios 

def getch(): 
    fd = sys.stdin.fileno() 
    old_settings = termios.tcgetattr(fd) 
    try: 
     tty.setraw(sys.stdin.fileno()) 
     ch = sys.stdin.read(1) 
    finally: 
     termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 
    return ch 

key = "" 
sys.stdout.write('Password :: ') 
while True: 
    ch = getch() 
    if ch == '\r': 
     break 
    key += ch 
    sys.stdout.write('*') 
print 
print key 
2

爲了解決這個問題,我寫這個小模塊pyssword掩蓋在用戶輸入密碼提示。它適用於Windows。代碼如下:

from msvcrt import getch 
import getpass, sys 

def pyssword(prompt='Password: '): 
    ''' 
     Prompt for a password and masks the input. 
     Returns: 
      the value entered by the user. 
    ''' 

    if sys.stdin is not sys.__stdin__: 
     pwd = getpass.getpass(prompt) 
     return pwd 
    else: 
     pwd = ""   
     sys.stdout.write(prompt) 
     sys.stdout.flush()   
     while True: 
      key = ord(getch()) 
      if key == 13: #Return Key 
       sys.stdout.write('\n') 
       return pwd 
       break 
      if key == 8: #Backspace key 
       if len(pwd) > 0: 
        # Erases previous character. 
        sys.stdout.write('\b' + ' ' + '\b')     
        sys.stdout.flush() 
        pwd = pwd[:-1]      
      else: 
       # Masks user input. 
       char = chr(key) 
       sys.stdout.write('*') 
       sys.stdout.flush()     
       pwd = pwd + char 
+0

「雖然這個鏈接可能回答問題,最好在這裏包含答案的重要部分,並提供參考鏈接。如果鏈接的頁面發生變化,僅鏈接答案可能會失效。「 – Ghost

+0

按請求包含的代碼! –

0

下面的代碼提供了用asterix替換寫入的字符並允許刪除錯誤鍵入的字符。 asterixes的數量反映了輸入字符的數量。

import getpass 
key = getpass.getpass('Password :: ') 
+0

雖然您的代碼片段可能會解決問題,但您應該描述代碼的用途(它是如何解決問題的)。此外,您可能需要檢查https://stackoverflow.com/help/how-to-answer –