Python 调试相关

错误处理

与一般的语言一样:

1
2
3
4
5
6
7
8
9
try:
print('try...')
r = 10 / 0
print('result:', r)
except BaseException as e:
print('except:', e)
finally:
print('finally...')
print('END')

结果:

1
2
3
4
try...
('except:', ZeroDivisionError('integer division or modulo by zero',))
finally...
END

Python 中异常类的父类是 BaseException ,详细关系图,可以看这里

try...catch...finally 和别的语言一样,finally 是一定执行的,catch 是在有异常出现的情况下才执行的,try 语句中出现异常就不往下执行了。

异常除了可以捕捉,也可以使用 raise 语句抛出。

1
2
3
4
5
6
7
8
9
10
class FooError(ValueError):
pass

def foo(s):
n = int(s)
if n==0:
raise FooError('invalid value: %s' % s)
return 10 / n

foo('0')

结果:

1
2
3
4
5
6
Traceback (most recent call last):
File "/Users/zhanglf/Documents/Python/practice/HelloWorld.py", line 13, in <module>
foo('0')
File "/Users/zhanglf/Documents/Python/practice/HelloWorld.py", line 10, in foo
raise FooError('invalid value: %s' % s)
__main__.FooError: invalid value: 0

使用 logging

引用:

1
import logging

配置:

1
logging.basicConfig(level=logging.ERROR)

使用:

1
2
3
4
logging.debug('debuf')
logging.info("info")
logging.warning('warning')
logging.error('error')

注意配置时使用大写,使用时使用小写。

配置的级别高时,使用低级别的是无效的。

如下是源码中的级别:

1
2
3
4
5
6
7
8
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

断点调试

在 Atom 上安装 python-debugge 插件。

运行需要调试的程序时,使用 ⌥ + R 调出调试窗口:

屏幕快照 2017-05-25 下午2.49.38

文档测试

这些注释会自动运行,如果结果与注释一致,没有反应,如果与注释不一致,就会提示错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Dict(dict):
'''
Simple dict but also support access as x.y style.

>>> d1 = Dict()
>>> d1['x'] = 100
>>> d1.x
100
>>> d1.y = 200
>>> d1['y']
200
>>> d2 = Dict(a=1, b=2, c='3')
>>> d2.c
'3'
>>> d2['empty']
Traceback (most recent call last):
...
KeyError: 'empty'
>>> d2.empty
Traceback (most recent call last):
...
AttributeError: 'Dict' object has no attribute 'empty'
'''
def __init__(self, **kw):
super(Dict, self).__init__(**kw)
#
# def __getattr__(self, key):
# try:
# return self[key]
# except KeyError:
# raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

def __setattr__(self, key, value):
self[key] = value

if __name__=='__main__':
import doctest
doctest.testmod()

注释了其中一段代码后,出现了错误,就会有如下的提示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
**********************************************************************
File "/Users/zhanglf/Documents/Python/practice/HelloWorld.py", line 11, in __main__.Dict
Failed example:
d1.x
Exception raised:
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1315, in __run
compileflags, 1) in test.globs
File "<doctest __main__.Dict[2]>", line 1, in <module>
d1.x
AttributeError: 'Dict' object has no attribute 'x'
**********************************************************************
File "/Users/zhanglf/Documents/Python/practice/HelloWorld.py", line 17, in __main__.Dict
Failed example:
d2.c
Exception raised:
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1315, in __run
compileflags, 1) in test.globs
File "<doctest __main__.Dict[6]>", line 1, in <module>
d2.c
AttributeError: 'Dict' object has no attribute 'c'
**********************************************************************
1 items had failures:
2 of 9 in __main__.Dict
***Test Failed*** 2 failures.

注释文档用 ''' 包起来使用。