第2章 2.4 捕获错误和问题

一、未对错误处理时:

import argparse
import sys

def main(number, other_number, output):
    result = number / other_number
    print(f'The result is {result}', file=output)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-n1', type=int, help='A number', default=1)
    parser.add_argument('-n2', type=int, help='Another number', default=1)
    parser.add_argument('-o', dest='output', type=argparse.FileType('w'), help='output file', default=sys.stdout)

    args = parser.parse_args()

    main(args.n1, args.n2, args.output)

  

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ python task_with_error_handling_step1.py -n1 3 -n2 2

The result is 1.5

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ python task_with_error_handling_step1.py -n1 25 -n2 5

The result is 5.0

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ python task_with_error_handling_step1.py -n1 5 -n2 2 -o result.txt

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ cat result.txt 

The result is 2.5

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ python task_with_error_handling_step1.py -n1 5 -n2 0 -o result.txt

Traceback (most recent call last):

  File "task_with_error_handling_step1.py", line 16, in <module>

    main(args.n1, args.n2, args.output)

  File "task_with_error_handling_step1.py", line 5, in main

    result = number / other_number

ZeroDivisionError: division by zero

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ cat result.txt 

 

二、捕获错误和问题:

import argparse
import sys
import logging

LOG_FORMAT = '%(asctime)s %(name)s %(levelname)s %(message)s'
LOG_LEVEL = logging.DEBUG

def main(number, other_number, output):
    logging.info(f'Dividing {number} between {other_number}')
    result = number / other_number
    print(f'The result is {result}', file=output)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-n1', type=int, help='A number', default=1)
    parser.add_argument('-n2', type=int, help='Another number', default=1)

    parser.add_argument('-o', dest='output', type=argparse.FileType('w'),
                        help='output file', default=sys.stdout)
    parser.add_argument('-l', dest='log', type=str, help='log file', default=None)

    args = parser.parse_args()
    if args.log:
        logging.basicConfig(format=LOG_FORMAT, filename=args.log, level=LOG_LEVEL)
    else:
        logging.basicConfig(format=LOG_FORMAT, level=LOG_LEVEL)
    try:
        main(args.n1, args.n2, args.output)
    except Exception as exc:
        logging.exception("Error running task")
        exit(1)

  

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ python task_with_error_handling_step4.py -n1 5 -n2 2

2022-04-10 23:09:39,507 root INFO Dividing 5 between 2

The result is 2.5

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ python task_with_error_handling_step4.py -n1 5 -n2 0

2022-04-10 23:09:43,978 root INFO Dividing 5 between 0

2022-04-10 23:09:43,979 root ERROR Error running task

Traceback (most recent call last):

  File "task_with_error_handling_step4.py", line 28, in <module>

    main(args.n1, args.n2, args.output)

  File "task_with_error_handling_step4.py", line 10, in main

    result = number / other_number

ZeroDivisionError: division by zero

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ 

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ python task_with_error_handling_step4.py -n1 5 -n2 0 -l error.log

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ python task_with_error_handling_step4.py -n1 5 -n2 0 -l error.log

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ 

(.venv) huangsiyangdeiMac:ch02 huangsiyang$ cat error.log 

2022-04-10 23:10:10,234 root INFO Dividing 5 between 0

2022-04-10 23:10:10,235 root ERROR Error running task

Traceback (most recent call last):

  File "task_with_error_handling_step4.py", line 28, in <module>

    main(args.n1, args.n2, args.output)

  File "task_with_error_handling_step4.py", line 10, in main

    result = number / other_number

ZeroDivisionError: division by zero

2022-04-10 23:10:15,561 root INFO Dividing 5 between 0

2022-04-10 23:10:15,561 root ERROR Error running task

Traceback (most recent call last):

  File "task_with_error_handling_step4.py", line 28, in <module>

    main(args.n1, args.n2, args.output)

  File "task_with_error_handling_step4.py", line 10, in main

    result = number / other_number

ZeroDivisionError: division by zero

 

三、日志的级别从不太关键到很关键分别为:DEBUG、INFO、WARNING、ERROR和CRITICAL。日志级别将设置记录消息所需的最小严重性。例如,如果严重性设置为WARNING,那么INFO的日志将不会记录。如下:

>>> import logging

>>> logging.basicConfig(level=logging.INFO)

>>> logging.warning('a warning message')

WARNING:root:a warning message

>>> logging.info('an intf message')

INFO:root:an intf message

>>> logging.debug('a debug message')

>>> 

#最终的debug日志将不会显示,因为级别比info级低。

  

posted @ 2022-04-10 23:20  轻舞飞洋  阅读(10)  评论(0编辑  收藏  举报