標籤:python運行環境、異常處理
1、Python的啟動
Python的命令格式:
python [option] ... [-c cmd | -m mod | file | -] [arg] ...
| 選項 |
描述 |
-J
|
啟動將從Python3中刪除或更改某些功能的警告 |
-B
|
阻止在匯入時建立.pyc或.pyo檔案 |
| -E |
忽略環境變數 |
-h
|
列印所有可用命令列選項的列表 |
-i
|
在程式執行後進入互動模式 |
| -m module |
以指令碼的形式運行庫模組module |
-O
|
最佳化模式 |
-OO
|
最佳化模式,在建立.pyo檔案時刪除文檔字串 |
-Q arg
|
指定Pyhthon2中除法運算子的行為,值為-Qold (預設), -Qwarn, -Qwarnall, -Qnew之一 |
-s
|
阻止將使用者網站目錄追加到sys.path |
-S
|
阻止包含site初始模組 |
-t
|
報告關於不一致的標籤使用警告 |
-tt
|
由於不一致的標籤使用而導致TabError異常 |
-u
|
未緩衝的二進位stdout和stdin |
-U
|
Unicode字面量,所有字串字面量都以Unicode形式處理(僅在Python2中使用) |
-v
|
詳細模式,跟蹤匯入語句 |
-V |
列印版本資訊 |
-x
|
跳過來源程式的第一行 |
-c cmd
|
以字串形式執行cmd |
2、doctest代碼測試模組
Doctest模組允許在文檔字串內嵌入注釋以顯示各種語句的期望行為,尤其是函數和方法的結構;此處的文檔字串看起來如同一個互動式shell會話;可用於測試文檔是否與主程式保持同步,或基於文檔對程式本身做測試。
自訂測試模組test.py:
[[email protected] home]# cat test.py #!/usr/bin/python3def add(num1,num2): ‘‘‘ >>> add(12,23) # ‘>>>‘之後需要有一空格 35 ‘‘‘ return num1+num2
使用doctest模組進行測試:
In [1]: import testIn [2]: import doctestIn [3]: doctest.testmod(test) #測試test.py模組Out[3]: TestResults(failed=0, attempted=1)In [4]: doctest.testmod(test,verbose=True)Trying: add(12,23)Expecting: 35ok1 items had no tests: test1 items passed all tests: 1 tests in test.add1 tests in 2 items.1 passed and 0 failed.Test passed.Out[4]: TestResults(failed=0, attempted=1)
也可以直接定義自測試模組:
[[email protected] home]# cat test.py #!/usr/bin/python3def add(num1,num2): ‘‘‘ >>> add(12,23) 35 ‘‘‘ return num1+num2if __name__ == ‘__main__‘: import doctest doctest.testmod()[[email protected] home]# python3 test.py #測試通過時不會顯示任何資訊[[email protected] home]# python3 test.py -v #輸出詳細資料Trying: add(12,23)Expecting: 35ok1 items had no tests: __main__1 items passed all tests: 1 tests in __main__.add1 tests in 2 items.1 passed and 0 failed.Test passed.
3、Python的異常處理
在一些程式設計語言中,錯誤是通過特殊的函數傳回值指出的,而Python使用異常,它是只有錯誤發生時執行的代碼。錯誤通常有:語法錯誤和邏輯錯誤兩大類。
| 語法錯誤:軟體的結構上有錯誤而導致不能被解譯器解釋或不能被編譯器編譯。 邏輯錯誤:由於不完整或不合法的輸入所致,也可能是邏輯無法產生、計算或者輸出結果需要的 過程無法執行等。
|
在Python中異常是一個對象,表示錯誤或意外,檢測到一個錯誤時,將觸發異常。Python可以通過異常傳導機制傳遞一個異常對象,發出一個異常情況出現的訊號;程式員也可以在代碼中手動觸發異常。Python異常可以理解為:程式員出現了錯誤而在正常控制流程以外採取的行為。這種處理可以分為兩個階段。
第一階段:解譯器觸發異常,此時當前程式流被打斷;
第二階段:異常處理,如忽略非致命性錯誤、減輕錯誤帶來的影響等。
這種處理方式的主要作用有:
錯誤處理:預設處理,停止程式,列印錯誤資訊;使用try語句處理異常並恢複 事件通知:用於發出有效狀態資訊 特殊情況處理:無法調整代碼去處理的現場 終止行為:try/finally語句可確保執行必須的結束處理機制 非常規控制流程程:異常是一種進階跳轉(goto)機制 |
在Python中,異常通過try語句來檢測,任何在try語句塊裡的代碼都會被監測,檢查有無異常。在本文中使用的是Python3作為示範。
try語句的主要有兩種形式:
try-except:檢測和處理異常。可以有多個except,支援使用else子句處理沒有探測異常的執行代碼 try-finally:僅檢測異常並做一些必要的清理工作。僅能有一個finally。 try語句的複合形式:try-except-finally。 |
try-except語句:
try: try_suiteexcept Exception [as reason]: except_suite In [1]: try: ...: f1=open(‘/tmp/a.txt‘,‘r‘) ...: except IOError as e: ...: print(‘Could nor open file‘,e) ...: Could nor open file [Errno 2] No such file or directory: ‘/tmp/a.txt‘
try-except-else語句:
except分句個數沒有限制,但else只能有一個;沒有異常發生時,else分句才會執行;沒有符合的except分句時,異常會向上傳遞到程式中的之前進入的try中或者道程式的頂層。
try: try_suiteexcept Exception1 [as reason]: suite_exception1except (Exception1, Exception2 ,Exception3 ...)[, reason]: suite ...except: suiteelse: else_suite
try-finally語句:
無論異常是否發生,finally子句都會執行;常用於定義必須進行的清理工作,如關閉檔案或斷開服務串連等;finally中的所有代碼執行完後會繼續向上一層引發異常。
try: try_suitefinally: finally_suite
try-except-else-finally語句:
try: try_suiteexcept Exception1: suite_exception1except (Exception1, Exception2 ,): suite23...else: else_suitefinally: finally_suite
| 分句形式 |
說明 |
except:
|
捕捉所有(其他)異常類型 |
except name [as e]:
|
只捕捉特定的異常 |
except (name1,name2):
|
捕捉所列出的異常 |
else: |
如果沒有異常就運行 |
finally:
|
總是運行此代碼塊 |
4、自訂異常
raise語句允許程式員強制拋出一個指定的異常。其文法格式為:
raise[someexception [ ,arg [, traceback]]]
someexception:異常的名字,僅能使用字串、類或執行個體;
args:以元組的形式傳遞給異常的參數;
traceback:異常出發時新產生的一個用於異常-正常化的追蹤記錄,多用於重新引發異常。
In [9]: try: ...: raise NameError(‘HiThere‘) #定義異常 ...: except NameError: ...: print(‘An except flew by!‘) ...: raise #觸發異常 ...: An except flew by!--------------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-9-9448df11d518> in <module>() 1 try:----> 2 raise NameError(‘HiThere‘) 3 except NameError: 4 print(‘An except flew by!‘) 5 raiseNameError: HiThere
大多數的標準異常都是由StandError派生的,其中有3個抽象的子類:
ArithmeticError |
由於算術錯誤引發的異常基類 OverflowError、ZeroDivisionError、FloatingPointError |
LookupError |
容器在接收到一個無效鍵或索引時引發異常 IndexError、KeyError |
EnvironmentError |
由於外部原因而導致的異常的基類 IOError、OSError、WindowsError |
自訂異常類:
自訂異常類通常分為兩大類:
自訂異常和多重繼承:從定義異常類和標準異常類進行多重繼承,例如: class customAttributeError(CustomException,AttributeError): pass 標準庫中使用的其它異常:如ArithmeticError、EnvironmentError等 |
assert語句通常用於在程式中引用調試代碼,文法格式為:
assert condition [, expression]
如果condition條件滿足,則assert不做任何操作;如果條件不滿足,則assert作為參數執行個體化AssertionError並引髮結果執行個體。
如果運行python時使用了-O最佳化選項,assert將是一個空操作,編譯器不為assert語句產生代碼 。運行python不使用-O選項,則__debug__內建變數為True,否則為False。
assert語句相當於下面代碼:
if __debug__: if not condition : raise AssertionError, <expression>
In [17]: assert len([‘my boy‘,12])>10 #條件len([‘my boy‘,12])>10不滿足依法預設異常--------------------------------------------------------------------------AssertionError Traceback (most recent call last)<ipython-input-17-cc0a09de885b> in <module>()----> 1 assert len([‘my boy‘,12])>10AssertionError: In [18]: assert range(4)==[0,1,2,3] #條件range(4)==[0,1,2,3]不滿足依法預設異常--------------------------------------------------------------------------AssertionError Traceback (most recent call last)<ipython-input-18-8b7aafe34e9e> in <module>()----> 1 assert range(4)==[0,1,2,3]AssertionError: In [19]: assert 1==1 #條件滿足,無輸出In [20]: assert range(4)==[0,1,2,3],IOError #條件不滿足,自訂異常為IOError--------------------------------------------------------------------------AssertionError Traceback (most recent call last)<ipython-input-20-49011133d0d8> in <module>()----> 1 assert range(4)==[0,1,2,3],IOErrorAssertionError: <class ‘OSError‘>
本文出自 “隨風而飄” 部落格,請務必保留此出處http://yinsuifeng.blog.51cto.com/10173491/1922560
Python運行環境與異常處理