Python3 study notes _E (abnormal, debugging)


Notes code can be run in Jupyter NoteBook (actually Jupyter-lab experience is great).

Recommended not to look, to be more hands to knock code. Eye over a thousand was better to hand read it again.

Jupiter run code related notes have been uploaded, downloaded from your own resources.

Errors and exceptions

'''
try: # 在try中的异常后的代码不会执行,程序会跳转到except中对异常进行处理
    pass # 需要捕获异常的代码块
except ExceptName as result: # 捕获异常ExceptName并将异常重命名为result
    pass # 对捕获异常的处理代码块
[
except Exp1 as result1: # except 捕获语句可以有多条,不冲突即可
    pass
...
]

Exception :是异常总和,所有异常都可被此异常捕获

当捕获的异常和设定的异常名称不对应时,会进行系统异常处理。

try: # 开启捕获
    pass
except Exp: # 捕获到异常时执行
    pass
else: # 没有捕获到异常时执行
    pass
finally: # 收尾工作,不论是否捕获到异常都会执行
    pass
'''

Capture multiple exceptions

'''
将异常名放入元组中存储
try:
    pass
except (err1, err2 [,err...]):
    pass
'''
# 异常 多个异常 例子
try:
    1/0
    open("sss0")
except NameError:
    print("try中出现NameError的异常")
except Exception as result:
    print("这里出现一个笼统的异常,{}".format(result))
else:
    print("try中没有异常时打印")
finally:
    print("不管try中是否有异常,都会执行finally")
print("异常测试结束")
# 例子结束
这里出现一个笼统的异常,division by zero
不管try中是否有异常,都会执行finally
异常测试结束

Unusual nesting

'''
内部try未捕获到异常,向外部逐层传递
try:
    try:
        pass
    except Exp1:
        pass
    pass
except Exp2:
    pass
'''

Custom exception

'''raise'''

# 用户自定义异常例子
class UserError(Exception):
    def __init__(self):
        print("这里是用户自定义的异常")
try:
    raise UserError
except UserError:
        print("抛出自定义异常")
else:
     print("没有异常")
# 例子结束
这里是用户自定义的异常
抛出自定义异常

Exception handling to throw an exception

'''
try:
    Error
except exception as result:
    if (pass):
        pass # 开启捕获异常
        print(result)
    else:
        pass # 重写抛出异常,此时的异常不会被捕获,交由系统处理
        raise
'''

debugging

print

the easiest

Assertion (assert)

In the program can use local print on it with assertions (assert)

assert expression, throwException

Expression expression should be True, otherwise, throw AssertionError: throwException

python -O fileName.py Close assertions

# assert 例子
def judger(name):
    # name!='username'为True,继续运行,False抛出your name is error!异常
    assert name != 'username','your name is error!'
    print('123456')
    
def main():
    judger('username')
    
if __name__=='__main__':
    main()
    
---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-1-4fda0f972b48> in <module>()
      9 
     10 if __name__=='__main__':
---> 11     main()
     12 


<ipython-input-1-4fda0f972b48> in main()
      6 
      7 def main():
----> 8     judger('username')
      9 
     10 if __name__=='__main__':


<ipython-input-1-4fda0f972b48> in judger(name)
      2 def judger(name):
      3     # name!='username'为True,继续运行,False抛出your name is error!异常
----> 4     assert name != 'username','your name is error!'
      5     print('123456')
      6 


AssertionError: your name is error!
logging

This article summarizes the modules for common good, has reference. Guide link

Address: https: //www.cnblogs.com/wf-linux/archive/2018/08/01/9400354.html

logging does not throw an exception, you can output debugging information to a file

logging record information can also specify the level (debug, info, warning, error)

Specify level = INFOwhen logging.debugit fails, the other levels set empathy.

logging through a simple configuration, output to a statement at the same time in different places, such as: console and file.

import logging

logging.basicConfig(level=[INFO,DEBUG,WARNING,ERROR,CRITICAL],
                               filename="your_log_file_name",
                               filemode='r,w,a',
                               format='your_log_format')

Parameters explanation:

level: Logging level
filename: log file
filemode: log file open mode
format: Logging Format

Parameters: role
% (levelno) s: printing log level value
% (levelname) s: the name of the print log level
% (pathname) s: print path currently executing program, in fact, the sys.argv [0]
% (filename) s: Print executing program name
% (funcName) s: current function of the printing log
% (lineno) d: printing log of the current line number
% (asctime) s: printing log time
% (thread) d: Print thread ID
% (threadName) s: print thread name
% (process) d: Print process ID
% (the message) S: print log information

# logging 简单例子
import logging


file_name='./Gnerate_files/logging_test.log'
logging.basicConfig(
    level=logging.INFO,
    filename=file_name,
    filemode='w+', # 这里针对本例子使用w,但是日志记录时不建议使用w
    format='%(lineno)s\t%(asctime)s: %(name)s: %(levelname)s: %(message)s')

logger = logging.getLogger(name=__name__)

logger.info("Start print log INFO")
logger.debug("Start print log DEBUG")
logger.warning("Start print log WARNING")
logger.info("the print log INFO is end")

print("日志文件内容:")
with open(file_name, 'r', encoding='utf-8', buffering=1024) as file:
    lines = file.readlines()
    for line in lines:
        print(line)

日志文件内容:
14	2020-02-07 13:18:03,459: __main__: INFO: Start print log INFO

16	2020-02-07 13:18:03,460: __main__: WARNING: Start print log WARNING

17	2020-02-07 13:18:03,460: __main__: INFO: the print log INFO is end
'''logger中添加StreamHandler,可以将日志输出到屏幕上'''
# 将日志同时输出到屏幕和日志文件例子
import logging

file_name = './Gnerate_files/logging_test_f_c.log'
loggerc = logging.getLogger(__name__)
loggerc.setLevel(level=logging.INFO)
handler = logging.FileHandler(file_name, mode='w+', encoding='utf-8')
handler.setLevel(logging.INFO)
formatter = logging.Formatter(
    '%(asctime)s: %(name)s %(levelname)s %(message)s')
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
loggerc.addHandler(handler)
loggerc.addHandler(console)

loggerc.info("Start print log INFO")
loggerc.debug("Start print log DEBUG")
loggerc.warning("Start print log WARNING")
loggerc.info("the print log INFO is end")

print("日志文件内容:")
with open(file_name, 'r', encoding='utf-8', buffering=1024) as file:
    lines = file.readlines()
    for line in lines:
        print(line)
Start print log INFO
Start print log WARNING
the print log INFO is end


日志文件内容:
2020-02-07 13:18:10,353: __main__ INFO Start print log INFO

2020-02-07 13:18:10,355: __main__ WARNING Start print log WARNING

2020-02-07 13:18:10,356: __main__ INFO the print log INFO is end
pdb debugging

pdb debugger has an obvious flaw is for multi-threaded remote debugging and other support was not good enough,

And there is no more intuitive interface display, not suitable for large python project.

pdb operation instruction

command Logogram Features annotation
break b Set a breakpoint no
continue c Continue program execution no
list l View current line of code no
step s Enter the function no
return r Executing code from the current until the function returns no
quit q Termination and exit no
next n The next line no
print p Print variable values no
help h help no
args a View incoming parameters no
  Enter Repeat last command no
break b Show all breakpoints no
break lineno b lineno Set a breakpoint at the specified line no
break file:lineno b file:lineno Set a breakpoint in the line of the specified file no
clear num   Delete the specified breakpoints The line number num here is not to add a breakpoint, but the number of breakpoints
bt   View function call stack frame no

pdb interactive debugger

import pdb

pdb.run (funcName (attribute)) # where s need to press in the pdb then L can, or will not display the code

pdb buried point program

import pdb

pdb.set_trace () # When the program encounters these words when entering the commissioning

发布了13 篇原创文章 · 获赞 0 · 访问量 25

Guess you like

Origin blog.csdn.net/qq_34764582/article/details/104940438