Python从门到精通(二):包装-02-异常处理和日志

网友投稿 344 2022-08-28


Python从门到精通(二):包装-02-异常处理和日志

相比java,python的异常和java中不同,python主要是防止程序异常被中止。一旦被catch后它还行往下执行。

一、异常

1.1、忽略

pass这个关键字相当于一个占位符,好比TODO是一样的,只表示此行什么也不做,不代表其它的行代码不执行;

try: print(5/0)except ZeroDivisionError: pass print("ddd") #这行还是可以正常执行的

1.2、捕获

def parse_int(s): try: n = int(v) except Exception as e: print('Could not parse, Reason:', e) parse_int('30') ##Reason: name 'v' is not defined

1.3、异常链

try: client_obj.get_url(url)except (URLError, ValueError, SocketTimeout): client_obj.remove_url(url)

try: client_obj.get_url(url)except (URLError, ValueError): client_obj.remove_url(url)except SocketTimeout: client_obj.handle_url_timeout(url)

try: f = open(filename)except OSError: pass

1.4、自定义

class NetworkError(Exception): passclass HostnameError(NetworkError): passclass CustomError(Exception): def __init__(self, message, status): super().__init__(message, status) self.message = message self.status = status

try: msg = s.recv()except TimeoutError as e: print(e)except RuntimeError as e: print(e.args)

1.5、抛出

try: raise RuntimeError('It failed') #抛出新异常-raise Errorexcept RuntimeError as e: print(e.args)

def example(): try: int('N/A') except ValueError: print("Didn't work") raise #捕获后再抛出

二、异常的显示方式

2.1、打印信息

try: print(5/0)except ZeroDivisionError as e: print(e.args)

2.2、控制台警告

import warningswarnings.simplefilter('always')def func(x, y, log_file=None, debug=False): if log_file is not None: warnings.warn('log_file argument deprecated', DeprecationWarning)func(1, 2, 'a')#第一行日志输出warn内容,第二行输出代码内容/Users/liudong/personCode/python/pythonTest/app/base/base_type.py:5: UserWarning: log_file argument deprecated warnings.warn('log_file argument deprecated')

2.2、存储文件

import json;numbers = [2,3,4,5,6];fileName = "numbers.json";with open(fileName, "w") as fileObj: json.dump(numbers, fileObj);with open(fileName, "r") as fileObj: number1 = json.load(fileObj);

三、日志

需要用到logging库。

3.1、硬编码日志

默认会输出到当前文件夹下。

import loggingdef main(): # Configure the logging system logging.basicConfig( filename='app.log', level=logging.ERROR # level = logging.WARNING, # format = f'%(levelname)s:%(asctime)s:%(message)s' ) host_name = 'python.org' item = 'spam' file_name = 'data.csv' mode = 'r' logging.critical(f'Host {host_name} unknown') logging.error(f"Couldn't find {item}") logging.warning('Feature is deprecated') logging.info(f'Opening file {file_name}, mode={mode}') logging.debug('Got here')if __name__ == '__main__': main()

CRITICAL:root:Host python.org unknownERROR:root:Couldn't find 'spam'CRITICAL:2020-06-03 08:21:28,334:Host python.org unknownERROR:2020-06-03 08:21:28,335:Couldn't find spamWARNING:2020-06-03 08:21:28,335:Feature is deprecatedCRITICAL:root:Host python.org unknownERROR:root:Couldn't find spam

3.2、采用配置文件来配置日志配置

logging.basicConfig( config_call())def config_call(): import logging.config logging.config.fileConfig('log_config.ini')

[loggers]keys=root[handlers]keys=defaultHandler[formatters]keys=defaultFormatter[logger_root]level=INFOhandlers=defaultHandlerqualname=root[handler_defaultHandler]class=FileHandlerformatter=defaultFormatterargs=('app.log', 'a')[formatter_defaultFormatter]format=%(levelname)s:%(name)s:%(message)s

3.3、自定义工具类

import logginglog = logging.getLogger(__name__)log.addHandler(logging.NullHandler())def func(): log.critical('A Critical Error!') log.debug('A debug message')#以下是三种不同的实现方式logging.basicConfig()func()logging.basicConfig(level=logging.ERROR)func()#创建模块logging.getLogger('log_func').level=logging.DEBUGfunc()


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python 设计模式:单例模式(python能做什么)
下一篇:Java中定时器Timer致命缺点案例详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~