python异常处理与断言
目录:
1.异常处理
2.断言(assert)
3.日志模块(logging)
4.修改之前的车票信息查询,把日志模块、异常处理加进去
1.异常处理
代码如下:
语法:
try:
pass #可能出现异常的语句
except Exception as e: #Exception 全部异常的通称
print(e)
finally: #可选项,不管有没有异常,finally里面的语句都执行
pass
#python 异常处理 try: print("try:") s=input("input:") b=int(s) c=int(input("input2:")) s2=b/c id=int(input("id:")) print([1,2,3][id]) except ValueError as e1: print("ValueError:") print(e1) except ZeroDivisionError as e2: print("ZeroDivisionError:") print(e2) except Exception as e: print(e) finally: #不管有没有异常,finally里面的语句都执行 print("finally") print("自己定义错误提示".center(20,"*")) try: print("try:") s=input("input:") b=int(s) c=int(input("input2:")) s2=b/c id=int(input("id:")) print([1,2,3][id]) except ValueError: print("ValueError:") print("输入的值不能转换成整数:") except ZeroDivisionError: print("ZeroDivisionError:") print("被除数不能为0") except Exception as e: print(e) finally: print("finally")
2.断言(assert)
如果没有出错,断言语句不执行,不满足条件,不往下走
运行加-O 忽略全部的断言(不执行断言)
#断言assert print("断言assert:") try: print("try:") a=input("input:") assert a.isdigit(),"输入的a不合法!" b=int(a) assert b!=0,"除数不为0!" r=10/b print("result:",r) id=int(input("id:")) l=[1,2,3] assert id in range(len(l)),"索引超出范围!" print(l[id]) except AssertionError as e: print(e) finally: #不管有没有异常,finally里面的语句都执行 print("finally")
3.日志模块(logging)
常用日志级别:info(通知)、debug(调试)、error(错误)、warning(警告)、critical(严重错误)
#日志模块logging import logging logging.basicConfig( #日志级别 level=logging.DEBUG, #日志格式 #时间、代码、行号、日志级别、日志信息 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', #日志时间格式 #datefmt='%a, %d %b %Y %H:%M:%S', #日志存放目录 filename='logfile.log', #打开日志文件的方式 filemode="a" ) logging.debug("这是一个调试信息") logging.info("这是一个通知信息") logging.warning("这是一个警告信息") logging.error("这是一个错误信息") logging.critical("这是一个严重错误信息")
4.修改之前的车票信息查询,把日志模块、异常处理加进去
import requests import logging from prettytable import PrettyTable logging.basicConfig( #日志级别 level=logging.DEBUG, #日志格式 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', #日志存放目录 filename='logfile.log', #打开日志文件的方式 filemode="a" ) url="https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9090" try: txt=requests.get(url).text except: print("网络未连接!") #print(txt) inf=txt[:-2].split("@")[1:] #print(inf) stations={} for record in inf: rlist=record.split("|") stations[rlist[2]]={"cn":rlist[1],"qp":rlist[3],"jp":rlist[4]} #把车站编码当作key def getcode(t): while True: s1=input("%s站:"%t) r1=[] for id,station in stations.items(): if s1 in station.values(): r1.append((id,station)) if r1: break print("没有这个车站!") print("请重新输入!") if len(r1)==1: sid=r1[0][0] else: print("你输入的条件比较模糊,请在以下站中进行选择:") for i in range(len(r1)): print(i+1,r1[i][1]["cn"]) sel=int(input("你的选择:"))-1 sid=r1[sel][0] return sid fromid=getcode("出发") toid=getcode("到达") fdate=input("出发日期(格式:2019-01-01):").strip() qurl=("https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=%s&leftTicketDTO.from_station=%s&leftTicketDTO.to_station=%s&purpose_codes=ADULT")%(fdate,fromid,toid) print(qurl) print("你输入的查询条件是:出发站:{},到达站:{}".format(fromid,toid)) ainf=requests.get(qurl).json()["data"]["result"] #json文件存储当前从出发站到目的站的所有车次的详细信息 result=[] gaotie=[] huoche=[] for i in ainf: list=i.split("|") checi=list[3] chufa=stations[list[6]]["cn"] mudi=stations[list[7]]["cn"] ftime=list[8] dtime=list[9] sw=list[32] yd=list[31] rw=list[23] yw=list[26] wuzuo=list[28] ed=list[30] yz=list[29] result.append((checi,chufa,mudi,ftime,dtime,ed,yz,wuzuo,yw,rw,yd,sw)) if checi[0] in ["G","D"]: gaotie.append([checi,chufa,mudi,ftime,dtime,sw,yd,ed]) else: huoche.append([checi,chufa,mudi,ftime,dtime,yz,yw,rw,wuzuo]) #print(result) while True: print("请输入查看信息:1、全部 2、高铁、动车 3、火车 4、退出") show=int(input("请选择:")) if show==1: table=PrettyTable(["车次","出发站","目的站","发车时间","到达时间","商务座","一等座","二等座","硬座","硬卧","软卧","无座"]) for i in result: table.add_row([i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8],i[9],i[10],i[11]]) print(table) elif show==2: table=PrettyTable(["车次","出发站","目的站","发车时间","到达时间","商务座","一等座","二等座"]) for i in gaotie: table.add_row([i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7]]) print(table) elif show==3: table=PrettyTable(["车次","出发站","目的站","发车时间","到达时间","硬座","硬卧","软卧","无座"]) for i in huoche: table.add_row([i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8]]) print(table) elif show==4: print("查询结束!") break else: print("输入错误请重新输入!")
日志记录查看: