用星号屏蔽python中的用户输入 [英] Masking user input in python with asterisks

查看:462
本文介绍了用星号屏蔽python中的用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用星号掩盖用户在IDLE中输入的内容,以使周围的人看不到他们正在输入/已输入的内容.我正在使用基本的原始输入来收集他们输入的内容.

I am trying to mask what the user types into IDLE with asterisks so people around them can't see what they're typing/have typed in. I'm using basic raw input to collect what they type.

key = raw_input('Password :: ')

用户键入密码后,出现理想的IDLE提示符:

Ideal IDLE prompt after user types password:

Password :: **********

推荐答案

根据操作系统的不同,如何从用户输入中获取单个字符以及如何检查回车符将有所不同.

Depending on the OS, how you get a single character from user input and how to check for the carriage return will be different.

请参阅此帖子: Python从用户读取单个字符

例如,在OSX上,您可以这样:

On OSX, for example, you could so something like this:

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

这篇关于用星号屏蔽python中的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆