python的getpass模块

getpass 模块


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/


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值