Python编程快速上手10章断言和日志

抛出异常
当 Python 试图执行无效代码时,就会抛出异常。在第 3 章中,你已看到如何使
用 try 和 except 语句来处理 Python 的异常,这样程序就可以从你预期的异常中恢复。
raise 语句包含以下部分:
• raise 关键字;
• 对 Exception 函数的调用;
• 传递给 Exception 函数的字符串,包含有用的出错信息。

>>> raise Exception('This is the error message.')
Traceback (most recent call last):
	File "<pyshell#191>", line 1, in <module>
		raise Exception('This is the error message.')
Exception: This is the error message.

断言
“断言”是一个心智正常的检查,确保代码没有做什么明显错误的事情。这些
心智正常的检查由 assert 语句执行。如果检查失败,就会抛出异常。
assert语句包含以下部分:
• assert 关键字;
• 条件(即求值为 True 或 False 的表达式);
• 逗号;
• 当条件为 False 时显示的字符串。

>>> podBayDoorStatus = 'open'
>>> assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
>>> podBayDoorStatus = 'colse'
>>> assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
Traceback (most recent call last):
	File "<pyshell#10>", line 1, in <module>
		assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".'
AssertionError: The pod bay doors need to be "open".

禁用断言
在运行 Python 时传入-O 选项,可以禁用断言。

日志
使用日志模块

import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')
#level=控制哪个级别的格式,forma=时间,级别,显示的信息
logging.debug('Start of program')
DEBUG  logging.debug() 
INFO  logging.info()  
WARNING  logging.warning() 
ERROR  logging.error()  
CRITICAL  logging.critical()

禁用日志
logging.CRITICAL加在显示之前。

将日志记录到文件

import logging
logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='
%(asctime)s - %(levelname)s - %(message)s')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值