python 3次登录
1 #!/usr/bin/env python 2 #-*- encoding: utf-8 -*- 3 4 import sys 5 import os 6 import getpass 7 import platform 8 9 10 # 全局变量 11 retry_limit = 3 # 登录重试次数 12 retry_count = 0 # 计数器 13 14 account_file = 'account.txt' 15 lock_file = 'account_lock.txt' 16 17 def lock(user): 18 lock_check = open(lock_file, 'r') # 打开account_lock.txt,检查用户是否已经存在文件中 19 20 for line in lock_check.readlines(): # 循环读取文件内容 21 if user == line.strip('\n'): # 去掉指定字符,并且判断是用户名是否和文件中的文件名一致 22 sys.exit('\033[35mUser %s is locked!!!\033[0m' % user) # 存在则直接退出并打印输出提示 23 24 lock_check.close() # 关闭打开的文件流 25 26 27 def login(user, passwd): 28 global retry_count # 函数内要改变全局变量的值 "retry_count += 1",需要加上global 关键字 29 30 file = open(account_file, 'r') 31 match_flag = False 32 33 for line in file.readlines(): 34 username, password = line.strip('\n').split() 35 36 if user == username and passwd == password: 37 print 'hello, %s !!' % username 38 match_flag = True 39 break 40 41 file.close() 42 43 if match_flag == False: 44 print 'sorry,%s is unmatched' % username 45 retry_count += 1 46 else: 47 print 'wlecome login my learning system!' 48 sys.exit(0) 49 50 51 def main(): 52 53 # 清屏操作,判断当前运行环境在什么平台下 54 if platform.system() != 'Windows': 55 os.system('clear') 56 else: 57 os.system('cls') 58 59 60 while retry_count < retry_limit: 61 username = raw_input('username: ') 62 lock(username) 63 password = getpass.getpass('password: ') # 用getpass模块中的getpass方法来实现输入密码时和Linux一样 64 login(username, password) 65 else: 66 print "you account %s is locked!!!" % username 67 g = open(lock_file,'a') 68 g.write(username) 69 g.write('\n') 70 g.close() 71 72 if __name__ == '__main__': 73 main() 74 75 76
posted on 2016-12-20 00:51 augustyang 阅读(288) 评论(0) 编辑 收藏 举报