python斷言的使用

lsq_008發表於2016-09-14
為了人工丟擲一個異常,可以使用斷言assert,如下:
#coding=utf-8

def testAssert(path):
import os
assert isinstance(path,str),'Need string'
if os.path.isdir(path) == True:
print path + ' is a dir!'
return path
else:
return "Not dir!"

if __name__ == '__main__':
print testAssert(2)

測試如下:
D:\work\bjmobile\daily_report>python test.py
Traceback (most recent call last):
  File "test.py", line 13, in
    print testAssert(2)
  File "test.py", line 5, in testAssert
    assert isinstance(path,str),'Need string'
AssertionError: Need string

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10972173/viewspace-2125003/,如需轉載,請註明出處,否則將追究法律責任。

相關文章