getpass 模块
getpass 模块提供了平台无关的在命令行下输入密码的方法.
getpass(prompt) 会显示提示字符串, 关闭键盘的屏幕反馈, 然后读取密码.
如果提示参数省略, 那么它将打印出 "Password:".
getuser() 获得当前用户名, 如果可能的话.
例子1:
getpass 模块提供了平台无关的在命令行下输入密码的方法.
getpass(prompt) 会显示提示字符串, 关闭键盘的屏幕反馈, 然后读取密码.
如果提示参数省略, 那么它将打印出 "Password:".
getuser() 获得当前用户名, 如果可能的话.
例子1:
import getpass
usr = getpass.getuser()
pwd = getpass.getpass("enter password for user %s: " % usr)
print usr, pwd
enter password for user mulder:
mulder trustno1
例子2:
import getpass
p = getpass.getpass(prompt='What is your favorite color? ')
if p.lower() == 'blue':
print 'Right. Off you go.'
else:
print 'Auuuuugh!'
输出
$ python getpass_prompt.py
What is your favorite color?
Right. Off you go.
$ python getpass_prompt.py
What is your favorite color?
Auuuuugh!
getpass()使用sys.stdout来打印提示字符串,如果程序会在sys.stdout生成有用的输出,将提示语发送到另一个流会更好,如sys.stderr,重定向
import getpass
import sys
p = getpass.getpass(stream=sys.stderr)
print 'You entered:', p
$ python getpass_stream.py >/dev/null
Password:
无终端使用
$ echo "sekret" | python getpass_defaults.py
Traceback (most recent call last):
File "getpass_defaults.py", line 34, in
p = getpass.getpass()
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/getpass.py", line 32, in unix_getpass
old = termios.tcgetattr(fd) # a copy to save
termios.error: (25, 'Inappropriate ioctl for device')
要由调用者检测输入流并非一个tty的情况使用下面的:
import getpass
import sys
if sys.stdin.isatty():
p = getpass.getpass('Using getpass: ')
else:
print 'Using readline'
p = sys.stdin.readline().rstrip()
print 'Read: ', p
With a tty:
$ python ./getpass_noterminal.py
Using getpass:
Read: sekret
Without a tty:
$ echo "sekret" | python ./getpass_noterminal.py
Using readline
Read: sekret
转自:http://nulijiabei.blog.163.com/blog/static/2052400862012130411699/