【Python】getpass模块关闭屏幕输出密码
源码: Lib/getpass.py
getpass 包含两个函数:
1:getpass.getpass(prompt=’Password: ‘, stream=None)
|
1 2 3 4 5 6 |
>>> import getpass >>> pwd = getpass.getpass() Password: >>> print (pwd) 123456 >>> |
参数:prompt,默认为“Password”,当然也可以显示你想要看到的内容
|
1 2 3 4 5 6 |
>>> import getpass >>> str = getpass.getpass("input your string:") input your string: >>> print (str) China >>> |
参数:stream(Windows系统忽略此参数)
在Linux/Unix系统, 提示符会写入到类文件流中,默认写入到/dev/tty, 如果写入不了的话,会写入到sys.stderr中。
备注: 通过IDLE中来调getpass函数,会显示输入的密码,在Python Shell也是一样且有警告。windows在cmd命令行下可以正常隐藏密码。Python Shell测试如下:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
>>> import getpass >>> pwd = getpass.getpass() Warning (from warnings module): File "D:\Program Files\Python34\lib\getpass.py", line 101 return fallback_getpass(prompt, stream) GetPassWarning: Can not control echo on the terminal. Warning: Password input may be echoed. Password: helloword >>> print (pwd) helloword >>> |
2:getpass.getuser()
Python官方文档大致是这样描述的:该函数按顺序检查环境变量LOGNAME,USER,LNAME和USERNAME,并返回第一个设置为非空字符串的值。
|
1 2 3 4 5 |
>>> import getpass >>> >>> getpass.getuser() 'root' >>> |