1. 程式人生 > >Python錯誤、調試

Python錯誤、調試

nbsp 方式 evel conf 解釋器 err tran debug nal

1.錯誤處理

使用try except finally

try:
    i = 10/0
except ZeroDivisionError, e:
    print "ZeroDivisionError", e
finally:
    print "Finally"
ZeroDivisionError integer division or modulo by zero
Finally

錯誤類型(含warning)

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      
+-- StopIteration +-- StandardError | +-- BufferError | +-- ArithmeticError | | +-- FloatingPointError | | +-- OverflowError | | +-- ZeroDivisionError | +-- AssertionError | +-- AttributeError | +-- EnvironmentError
| | +-- IOError | | +-- OSError | | +-- WindowsError (Windows) | | +-- VMSError (VMS) | +-- EOFError | +-- ImportError | +-- LookupError | | +-- IndexError | | +-- KeyError | +-- MemoryError
| +-- NameError | | +-- UnboundLocalError | +-- ReferenceError | +-- RuntimeError | | +-- NotImplementedError | +-- SyntaxError | | +-- IndentationError | | +-- TabError | +-- SystemError | +-- TypeError | +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning

logging模塊記錄錯誤信息

import logging

def Test(i):
    try:
        j = 10/i
    except StandardError, e:
        print "standardError"
        logging.exception(e)
    print "Test"


Test(0)
print "End"
standardError
ERROR:root:integer division or modulo by zero
Test
End
Traceback (most recent call last):
  File "F:/PyProject/test2.py", line 9, in Test
    j = 10/i
ZeroDivisionError: integer division or modulo by zero

自定義錯誤類型繼承內置錯誤類型

class FooError(StandardError):
pass


def foo(s):
n = int(s)
if n == 0:
raise FooError("value is %s" % s)


foo("0")
Traceback (most recent call last):
  File "F:/PyProject/test2.py", line 18, in <module>
    foo("0")
  File "F:/PyProject/test2.py", line 15, in foo
    raise FooError("value is %s" % s)
__main__.FooError: value is 0

另 可以在except中捕獲錯誤之後 使用 raise 將錯誤拋給頂層調用者去處理

2.調試

assert 斷言

def foo(n):
    i = int(n)
    assert i != 0, "catch assert"
    return i


a = foo("0")
print a
Traceback (most recent call last):
  File "F:/PyProject/test2.py", line 13, in <module>
    a = foo("0")
  File "F:/PyProject/test2.py", line 10, in foo
    assert i != 0, "catch assert"
AssertionError: catch assert

相當於 if i != 0 為True 繼續執行 反之 拋出 AssertionError並中斷運行

關閉assert方法 是 在python 解釋器中加參數 -O 來將python編譯成pyo文件

logging不會拋出錯誤 但是會打日誌 默認logging級別是WARNING 通過logging.basicConfig(level=logging.日誌等級)修改默認值

logging模塊將日誌打印到了標準輸出中,且只顯示了大於等於設定級別的日誌 (日誌級別等級CRITICAL > ERROR > WARNING > INFO > DEBUG >NOTSET)

默認格式為 Logger:輸出內容

啟動Python的調試器pdb,讓程序以單步方式運行,可以隨時查看運行狀態

以參數-m pdb啟動程序後,pdb定位到下一步要執行的代碼。輸入命令l來查看代碼。任何時候都可以輸入命令p 變量名來查看變量。

pdb.set_trace() 這個方法也是用pdb,但是不需要單步執行,我們只需要import pdb,然後,在可能出錯的地方放一個pdb.set_trace(),就可以設置一個斷點,行代碼,程序會自動在pdb.set_trace()暫停並進入pdb調試環境,可以用命令p查看變量,或者用命令c繼續運行

Python錯誤、調試