python 密码输入显示星号_[145]python实现控制台密码星号输入
import msvcrt, sys, os
print('password: ', end='', flush=True)
li = []
while 1:
ch = msvcrt.getch()
#回车
if ch == b'\r':
msvcrt.putch(b'\n')
print('输入的密码是:%s' % b''.join(li).decode())
break
#退格
elif ch == b'\x08':
if li:
li.pop()
msvcrt.putch(b'\b')
msvcrt.putch(b' ')
msvcrt.putch(b'\b')
#Esc
elif ch == b'\x1b':
break
else:
li.append(ch)
msvcrt.putch(b'*')
os.system('pause')
示例
一、raw_input()或input():
for python 2.x
[root@master test]# /usr/local/python2.7/bin/python test.py
Please input your password:123
your password is 123
[root@master test]# cat test.py
#!/usr/bin/python
# -*- coding=utf-8 -*-
#for python 2.x
#input = raw_input("Please input your password:")
#print "your password is %s" %input
for python 3.x
[root@master test]# /usr/local/python3.4/bin/python3 test.py
Please input your password:123
your password is 123
[root@master test]# cat test.py
#!/usr/bin/python
# -*- coding=utf-8 -*-
#for python 3.x
input = input("Please input your password:")
print ("your password is %s" %input)
Note:这种方法最简单,但是不安全,很容易暴露密码。
二、getpass.getpass():
for python 2.x
[root@master test]# /usr/local/python2.7/bin/python test.py
Please input your password:
your password is 123
[root@master test]# cat test.py
#!/usr/bin/python
# -*- coding=utf-8 -*-
import getpass
#for python 2.x
input = getpass.getpass("Please input your password:")
print "your password is %s" %input
for python 3.x
[root@master test]# /usr/local/python3.4/bin/python3 test.py
Please input your password:
your password is 123
[root@master test]# cat test.py
#!/usr/bin/python
# -*- coding=utf-8 -*-
import getpass
#for python 3.x
input = getpass.getpass("Please input your password:")
print ("your password is %s" %input)
Note:这种方法很安全,但是看不到输入的位数,让人看着有点不太习惯,而且没有退格效果。
三、termios:
for python 2.x
[root@master test]# /usr/local/python2.7/bin/python test.py
Enter your password:***
your password is 123
[root@master test]# cat test.py
#!/usr/bin/python
# -*- coding=utf-8 -*-
import sys, tty, termios
#for python 2.x
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
def getpass(maskchar = "*"):
password = ""
while True:
ch = getch()
if ch == "\r" or ch == "\n":
return password
elif ch == "\b" or ord(ch) == 127:
if len(password) > 0:
sys.stdout.write("\b \b")
password = password[:-1]
else:
if maskchar != None:
sys.stdout.write(maskchar)
password += ch
if __name__ == "__main__":
print "Enter your password:",
password = getpass("*")
print "your password is %s" %password
for python 3.x
[root@master test]# /usr/local/python3.4/bin/python3 test.py
Enter your password:
***your password is 123
[root@master test]# cat test.py
#!/usr/bin/python
# -*- coding=utf-8 -*-
import sys, tty, termios
#for python 3.x
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
def getpass(maskchar = "*"):
password = ""
while True:
ch = getch()
if ch == "\r" or ch == "\n":
return password
elif ch == "\b" or ord(ch) == 127:
if len(password) > 0:
sys.stdout.write("\b \b")
password = password[:-1]
else:
if maskchar != None:
sys.stdout.write(maskchar)
password += ch
if __name__ == "__main__":
print ("Enter your password:",)
password = getpass("*")
print ("your password is %s" %password)
Note:这种方法可以实现输入显示星号,而且还有退格功能,该方法仅在Linux上使用。
四、msvcrt.getch()
F:\Python\Alex\s12\zhulh>python test.py
Please input your password:
***
your password is:123
#!/usr/bin/python
# -*- coding=utf-8 -*-
import msvcrt,sys
def pwd_input():
chars = []
while True:
try:
newChar = msvcrt.getch().decode(encoding="utf-8")
except:
return input("你很可能不是在cmd命令行下运行,密码输入将不能隐藏:")
if newChar in '\r\n': # 如果是换行,则输入结束
break
elif newChar == '\b': # 如果是退格,则删除密码末尾一位并且删除一个星号
if chars:
del chars[-1]
msvcrt.putch('\b'.encode(encoding='utf-8')) # 光标回退一格
msvcrt.putch( ' '.encode(encoding='utf-8')) # 输出一个空格覆盖原来的星号
msvcrt.putch('\b'.encode(encoding='utf-8')) # 光标回退一格准备接受新的输入
else:
chars.append(newChar)
msvcrt.putch('*'.encode(encoding='utf-8')) # 显示为星号
return (''.join(chars) )
print("Please input your password:")
pwd = pwd_input()
print("\nyour password is:{0}".format(pwd))
sys.exit()
Note:这种方法可以实现输入显示星号,而且还有退格功能,该方法仅在Windows上使用。
在这里提供shell实现的输入密码显示星号的方法:
[root@master test]# sh ./passwd.sh
Please input your passwd: ***
Your password is: 123
[root@master test]# cat passwd.sh
#!/bin/sh
getchar() {
stty cbreak -echo
dd if=/dev/tty bs=1 count=1 2> /dev/null
stty -cbreak echo
}
printf "Please input your passwd: "
while : ; do
ret=`getchar`
if [ x$ret = x ]; then
echo
break
fi
str="$str$ret"
printf "*"
done
echo "Your password is: $str"
这里还有一个获取跨平台按键的例子:
class _Getch:
"""Gets a single character from standard input. Does not echo to the screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
try:
self.impl = _GetchMacCarbon()
except AttributeError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac
def __call__(self):
import sys, tty, termios
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
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
class _GetchMacCarbon:
"""
A function which returns the current ASCII key that is down;
if no ASCII key is down, the null string is returned. The
page http://www.mactech.com/macintosh-c/chap02-1.html was
very helpful in figuring out how to do this.
"""
def __init__(self):
import Carbon
Carbon.Evt #see if it has this (in Unix, it doesn't)
def __call__(self):
import Carbon
if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
return ''
else:
#
# The event contains the following info:
# (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
#
# The message (msg) contains the ASCII char which is
# extracted with the 0x000000FF charCodeMask; this
# number is converted to an ASCII character with chr() and
# returned
#
(what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
return chr(msg & 0x000000FF)
if __name__ == '__main__': # a little test
print 'Press a key'
inkey = _Getch()
import sys
for i in xrange(sys.maxint):
k=inkey()
if k<>'':break
print 'you pressed ',k
参考:https://www.cnblogs.com/Richardzhu/p/5162289.html
本文同步分享在 博客“周小董”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
python 密码输入显示星号_[145]python实现控制台密码星号输入相关推荐
- python怎么窗口显示文字_用python和pygame游戏编程入门-显示文字
上一节我们通过键盘可以控制角色移动,如果要让角色说话,那就要用到文字显示.Pygame可以直接调用系统字体,或者也可以使用TTF字体,TTF就是字体文件,可以从网上下载.为了使用字体,你得先创建一个F ...
- python 网页上显示数据_用Python实现网页数据抓取
需求: 获取某网站近10万条数据记录的相关详细信息. 分析:数据的基本信息存放于近1万个页面上,每个页面上10条记录.如果想获取特定数据记录的详细信息,需在基本信息页面上点击相应记录条目,跳转到详细信 ...
- python外星人入侵不显示子弹_【Python】python外星人入侵,武装飞船,代码写好后,不显示子弹...
按照书上写的武装飞船,写到能够左右移动了,但到了射击(装子弹)时候,按照书上的代码照搬了,运行时没显示代码有问题,但就是按了空格键,不见有子弹,其他都正常. 代码: alien_invasion.py ...
- python给定字符串显示奇数_字符串基础练习题80+道(原文及代码见文尾链接)
Python 字符串基础练习题80+道 1.编写一个Python程序来计算字符串的长度. 2.编写一个Python程序来计算字符串中的字符数(字符频率). Sample String:google.c ...
- python读取串口数据 绘图_使用Python串口实时显示数据并绘图的例子
使用pyserial进行串口传输 一.安装pyserial以及基本用法 在cmd下输入命令pip install pyserial 注:升级pip后会出现 "'E:Anaconda3Scri ...
- python的flask框架显示柱状图_使用Python的Flask框架,结合Highchart,动态渲染图表...
服务端动态渲染图表 参考文章链接:https://www.highcharts.com.cn/docs/dynamic-produce-html-page 参考文章是使用php写的,我这边改用pyth ...
- python画图程序没有图_解决python中使用plot画图,图不显示的问题
解决python中使用plot画图,图不显示的问题 对以下数据画图结果图不显示,修改过程如下 df3 = {'chinese':109, 'American':88, 'German': 66, 'K ...
- python怎么粘贴字进去_通过python粘贴到输入字段上
我很难找到一个合适的解决方案将我的输入粘贴到输入字段中.我正在使用库Xdo. 我在做什么? Python文件正在后台运行.在 程序从智能卡获取数据.在 返回的数据为数字/英语和泰语.在 然后在浏览器中 ...
- python字典输入学生信息_用Python创建一个学生字典并可以查询其中信息
展开全部 你可以试试这个---------------------------------------------------------- # -*- coding:UTF-8 -*- studen ...
- python软件安装及设置_入门Python——1.软件安装与基础语法
周末在家闲来无事,学了下Python.怕看过一遍就忘了,这里mark下. 一.Python的应用场景 1.网站开发 2.人工智能 机器学习 3.数据科学(如爬虫) 4.其它(绘图.图像处理) 二.软件 ...
最新文章
- python 模拟键盘_python+selenium模拟键盘输入
- oracle 报错pls 00405,oracle - 检查是否存在PLS-00405:在此上下文中不允许子查询 - 堆栈内存溢出...
- 华中C语言程序简答题,华中科技大学0911年C语言程序设计试卷.doc
- 世纪互联云和华为共同打造的数据中心是一个很好的一步标志!
- 捡起JavaScript(1)
- 为什么技术人一定要懂点“可信计算”?
- 解决 mysql>com.mysql.jdbc.PacketTooBigException: Packet for query is too large (12073681 > 4194304)
- hutool 取前12个月_Excel – 创建 12 个月的工资表模板,我只要 20 秒
- ASP.NET MVC 相关的社群与讨论区
- linux下keytool生成证书_生成证书命令keytool
- 分布式mysql 不支持存储过程_分布式数据库VoltDB对存储过程的支持
- Flink on K8s 在京东的持续优化实践
- Java实现单链表翻转
- 用python自制一个简单的答题程序
- 阿里3大营销模型:AIPL、FAST、GROW
- 使用Proteus 8.9仿真STM32F103流水灯实验
- SEO和SEM是什么?又有什么区别?
- 求ax2+bx+c=0方程的解,要求(1) a=0,不是二次方程。(2) b2-4ac=0,有两个相同的实根。(3)b2-4ac>0,有两个不等的实根。(4)b2-4ac<有两个共轭的复根
- 几种网赚项目引流的方法
- 嵌入式开发工程师需要掌握哪些知识呢?
热门文章
- 三年级竖式计算机应用题,三年级下册数学竖式计算1000题小学三年级下册数学应用题专项练习题100道...
- 20000条笑话保证笑死你
- 考研英语九附双语阅读:英国品牌美国遇冷 美国人不待见英国货?
- linux下docker的使用教程,Linux中docker的使用方法讲解
- 解决 Poi读取Excle报错 java.util.zip.ZipException: invalid stored block lengths
- 安卓系统命令 ftp服务器,安卓手机 ftp服务器
- 快速获取今天是星期几
- This scheduler instance (XXXXX) is still active but was recovered by another
- mysql timestamp毫秒_MySQL的Timestamp插入丢失毫秒的问题
- Promethus(普罗米修斯)监控