增加程序健壮性有两个办法:
with open 上下文管理器
with open('a.txt',encoding='utf-8')as file2:
data = file.read()
异常处理
异常也是一个类
异常捕获过程:
- 异常类把错误消息打包到一个对象
- 然后该对象会自动查找到调用栈
- 直到运行系统找到明确声明如何处理这些异常类的位置
所有异常继承自BaseException
Traceback显示了出错的位置,显示顺序和异常信息对象的传播方向是相反的。
class UserInputError(Exception):
def __init__(self, ErrorInfo):
super().__init__(self, ErrorInfo)
self.errorinfo = ErrorInfo
def __str__(self):
return self.errorinfo
userinput = 'a'
try:
if (not userinput.isdigit()):
raise UserInputError('用户输入错误')
except UserInputError as ue:
print(ue)
finally:
del userinput
#增加了健壮性的request
import requests
from pathlib import *
import sys
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
header = {'user-agent':ua}
myurl = 'http://movie.douban.com/top250'
try :
response = requests.get(myurl,headers=header)
except requests.exceptions.ConnectTimeout as e:
print(f"requests库超时")
sys.exit(1)
#将网页内容改为存入文件
#print(response.text)
#获取文件
p = Path(__file__)
pyfile_path = p.resolve().parent
#建立新的目录html
html_path=pyfile_path.joinpath('html')
if not html_path.is_dir():
Path.mkdir(html_path)
page = html_path.joinpath("douban.html")
#上下文管理器
try:
with open(page,"w",encoding="utf-8") as f:
f.write(response.text)
except FileNotFoundError as e:
print(f"文件无法打开,{e}")
except IOError as e:
print(f"读写文件出错,{e}")
except Exception as e:
print(e)