第十章异常

cardrun

def safe_float(object):
    'safe version of float()'
    try :
        retval=float(object)
    except (TypeError,ValueError) as diag:#python3中把‘,’换成‘as’
        retval=str(diag)
    return retval

def main():
    'handles all the data processing'
    log = open('cardlog.txt','w')
    try:
        ccfile=open('carddata.txt','r')
    except IOError as e:
        log.write('no txns this month\n')
        log.close()
        return
        
    txns=ccfile.readlines()
    ccfile.close()
    total=0.00
    log.write('account log:\n')
    
    for eachTxn in txns:
        result=safe_float(eachTxn)
        if isinstance(result,float):
            total+=result
            log.write('data...processed\n')
        else:
            log.write('ignored: &s'%result)
    print("$%.2f(new balance)"%(total))
    log.close()

if __name__=="__main__":
    main()
            

  cardrun1

def safe_float(object):
    'safe version of float()'
    try :
        retval=float(object)
    except (TypeError,ValueError) as diag:#python3中把‘,’换成‘as’
        retval=str(diag)
    else:
        log.write("***no exception caught\n")
    return retval

def main():
    'handles all the data processing'
    log = open('cardlog.txt','w')
    try:
        ccfile=open('carddata.txt','r')
    except IOError as e:
        log.write('no txns this month\n')
        log.close()
        return
    else:
        log.write("***no exception caught\n") 
        txns=ccfile.readlines()
        ccfile.close()
        total=0.00
        log.write('account log:\n')
        
        for eachTxn in txns:
            result=safe_float(eachTxn)
            if isinstance(result,float):
                total+=result
                log.write('data...processed\n')
            else:
                log.write('ignored: &s'%result)
        print("$%.2f(new balance)"%(total))
        log.close()

if __name__=="__main__":
    main()
            

  cardrun2

def safe_float(object):
    'safe version of float()'
    try :
        with float(object) as retval:
    except (TypeError,ValueError) as diag:#python3中把‘,’换成‘as’
        retval=str(diag)
    else:
        log.write("***no exception caught\n")
        
def main():
    'handles all the data processing'
    log = open('cardlog.txt','w')
    try:
        with open('carddata.txt','r') as ccfile
    except IOError as e:
        log.write('no txns this month\n')
        log.close()
        return
    else:
        log.write("***no exception caught\n") 
        txns=ccfile.readlines()
        ccfile.close()
        total=0.00
        log.write('account log:\n')
        
        for eachTxn in txns:
            result=safe_float(eachTxn)
            if isinstance(result,float):
                total+=result
                log.write('data...processed\n')
            else:
                log.write('ignored: &s'%result)
        print("$%.2f(new balance)"%(total))
        log.close()

if __name__=="__main__":
    main()
            

  9-12

import time#时间戳
import hashlib#hash加密
import pickle as p
import shelve as s

dictpassword={}#用于管理
dicttime={}#存储时间
dicthash={}#存储加密后的口令

path_password='datapassword.txt'#创建文件来保存信息
path_time="datatime.txt"
path_hash="datahash.txt"

def hash(str):#为字符串加密
    hl= hashlib.md5()
    hl.update(str.encode(encoding='utf-8'))
    return hl.hexdigest()

def write(dict,path):#将字典保存成文件
    file=open(path,"w")
    file.write(str(dict)) 
    file.close()

#从文件中读取字典
"""def read(dict,path):
    f = open('temp.txt','r')
    a = f.read()
    dict= eval(a)
   # f.close()
"""
    
def newuser(name):#创建新用户
    print("login desired: ",name)
    pwd=input("password: ")
    dictpassword[name]=pwd
    dicttime[name]=time.time()
    dicthash[name]=hash(pwd)
    write(dictpassword,path_password)
    write(dicthash,path_hash)
    write(dicttime,path_time)

def olduser(name):#老用户登录
    f = open('datapassword.txt','r')
    a = f.read()
    dictpassword= eval(a)
    pwd=input("password: ")
    password=dictpassword.get(name)
    f.close()
    if password==pwd:
        print("welcome back",name)
        if (time.time()-dicttime[name])<=14400:
            print("You already logged in at :",time.asctime( time.localtime(time.time()) ))
        dicttime[name]=time.time()
        write(dicttime,path_time)
    else:
        print("login incorrect")

def show():#输出所有信息
    f = open('datapassword.txt','r')
    f_=open("datatime.txt",'r')
    a = f.read()
    a_=f_.read()
    dictpassword= eval(a)
    datatime=eval(a_)
    for i in dictpassword:
        print(i,':',dictpassword[i],':',time.asctime(time.localtime((datatime[i]))))
        

def delete():#删除一个用户
    f = open('dictpassword.txt','r')
    a = f.read()
    dictpassword= eval(a)
    name=imput("you want delete: ")
    if name not in dictpassword:
        print(name,"don't exist!")
    else:
        del dictpassword[name]
        f.close()

def manege():#管理菜单
    prompt="""
(D)elete an user
(S)how all user's names,password and last time"""
    choice=input(prompt).strip()[0].lower()
    print("You picked: [%s]"%choice)
    if choice not in "ds":
        print("invalid option,try again")
    if choice=="d":delete()
    if choice=="s":show()

def picklesave(accountfile,db):
    f=open(accountfile,'w')
    p.dump(db,f)
    f.close()
    f=open(accountfile)
    accountdb=p.load(f)
    print(accountdb)

def shelve( accountfile,accountdb):
    accountdb=s.open(accountfile,'c')
    accountdb['data']=db
    accountdb.close()
    accountdb=s.open(accountfile,'r')
    print(accountdb['data'])

def showmenu():
    prompt="""
(L)ogin
(Q)uit
(M)anagement

Enter choice: """

    done=False
    while not done:
        chosen=False
        while not chosen:
            try:
                choice=input(prompt).strip()[0].lower()
            except:
                choice="q"
            print("You picked: [%s]"%choice)
            if choice not in "lqm":
                print("invalid option,try again")
            else:
                chosen=True

        if choice=="q":done=True
        if choice=="m":manege()
        if choice=="l":
            name=input("login: ")
            if name.isalnum()==False:
                print("name cannot contain " " or character")
            else:          
                f = open('datapassword.txt','r')
                a = f.read()
                dictpassword= eval(a)
                if name not in dictpassword:
                    f.close()
                    print(name,"don't exist!")
                    whether=input("Are you want to creat it? Y or N?").strip()[0].lower()
                    if whether=="y":
                        newuser(name)
                    else:
                        pass
                else:
                    f.close()
                    olduser(name)
    picklesave("pickletime",dicttime)

if __name__=="__main__":
    showmenu()

  

猜你喜欢

转载自www.cnblogs.com/dongyao-cufe/p/9905623.html