異常處理
有時候我們在寫程序的時候會出現錯誤或者異常,導致程序終止,如下這個例子:
#!/usr/bin/env python a = 2/0 print(a)
結果提示如下錯誤:
Traceback (most recent call last): File "002.py", line 2, in <module> a = 2/0 ZeroDivisionError: integer division or modulo by zero
上面提示被除數不能為0,從而導致程序運行中斷,為了能夠讓程序正常執行,我們可以添加tey...except...語句:
try: a = 2/0 print(a) except Exception as e: print("除數不能為0") #raise e # 把異常拋出來 finally: print("無論發生什么情況,都執行此步。") 結果: 除數不能為0 無論發生什么情況,都執行此步。
上面如果加上了raise e,則會把異常信息打印出來:ZeroDivisionError: integer division or modulo by zero。其中except部分是對錯誤信息進行處理,finally是不管之前有沒有異常,都會執行此步驟。
python標准異常類:
異常名稱 | 描述 |
---|---|
BaseException | 所有異常的基類 |
SystemExit | 解釋器請求退出 |
KeyboardInterrupt | 用戶中斷執行(通常是輸入^C) |
Exception | 常規錯誤的基類 |
StopIteration | 迭代器沒有更多的值 |
GeneratorExit | 生成器(generator)發生異常來通知退出 |
SystemExit | Python 解釋器請求退出 |
StandardError | 所有的內建標准異常的基類 |
ArithmeticError | 所有數值計算錯誤的基類 |
FloatingPointError | 浮點計算錯誤 |
OverflowError | 數值運算超出最大限制 |
ZeroDivisionError | 除(或取模)零 (所有數據類型) |
AssertionError | 斷言語句失敗 |
AttributeError | 對象沒有這個屬性 |
EOFError | 沒有內建輸入,到達EOF 標記 |
EnvironmentError | 操作系統錯誤的基類 |
IOError | 輸入/輸出操作失敗 |
OSError | 操作系統錯誤 |
WindowsError | 系統調用失敗 |
ImportError | 導入模塊/對象失敗 |
KeyboardInterrupt | 用戶中斷執行(通常是輸入^C) |
LookupError | 無效數據查詢的基類 |
IndexError | 序列中沒有沒有此索引(index) |
KeyError | 映射中沒有這個鍵 |
MemoryError | 內存溢出錯誤(對於Python 解釋器不是致命的) |
NameError | 未聲明/初始化對象 (沒有屬性) |
UnboundLocalError | 訪問未初始化的本地變量 |
ReferenceError | 弱引用(Weak reference)試圖訪問已經垃圾回收了的對象 |
RuntimeError | 一般的運行時錯誤 |
NotImplementedError | 尚未實現的方法 |
SyntaxError | Python 語法錯誤 |
IndentationError | 縮進錯誤 |
TabError | Tab 和空格混用 |
SystemError | 一般的解釋器系統錯誤 |
TypeError | 對類型無效的操作 |
ValueError | 傳入無效的參數 |
UnicodeError | Unicode 相關的錯誤 |
UnicodeDecodeError | Unicode 解碼時的錯誤 |
UnicodeEncodeError | Unicode 編碼時錯誤 |
UnicodeTranslateError | Unicode 轉換時錯誤 |
Warning | 警告的基類 |
DeprecationWarning | 關於被棄用的特征的警告 |
FutureWarning | 關於構造將來語義會有改變的警告 |
OverflowWarning | 舊的關於自動提升為長整型(long)的警告 |
PendingDeprecationWarning | 關於特性將會被廢棄的警告 |
RuntimeWarning | 可疑的運行時行為(runtime behavior)的警告 |
SyntaxWarning | 可疑的語法的警告 |
UserWarning | 用戶代碼生成的警告 |
模塊
模塊和目錄的區別,看整個文件夾里面是否有__init__.py文件,有就是模塊,沒有就是普通目錄。__init__.py一般是一個空文件。
通常一個.py文件我們就可以稱之為一個模塊。
a.py #!/usr/bin/env python def hello(): print("hello") hello() def world(): print("world") world() b.py #!/usr/bin/env python import a 運行python b.py結果: hello world
如上 ,當我們在b.py中將a.py作為模塊導入之后,在運行b.py的時候,直接會運行a.py里面的所有函數,但是如果我們只想要在b.py中調用a.py中指定函數的時候運行,就需要在a.py中加入if __name__ == "__main__":語句:
a.py #!/usr/bin/env python def hello(): print("hello") def world(): print("world") if __name__ == "__main__": hello() world() b.py #!/usr/bin/env python import a a.hello() a.world() 運行python b.py之后的結果: hello world
由上可以看出,加上if __name__ == "__main__":語句之后,就能滿足我們的需求。
總結:
1、文件夾里面需要有__init__.py文件的才能當做模塊使用。
2、if __name__ == "__main__":語句的使用。
內置模塊
datetime
import datetime # 下面我們使用的是datetime模塊下面的datetime模塊,所以使用的時候需要datetime.datetime,為了更方便的使用,也可以直接使用from datetime import datetime print(datetime.datetime.now()) # 打印當前時間 2018-04-23 09:33:32.055974 print(datetime.datetime.now().year) # 打印當前時間中的年份 2018 print(datetime.datetime.now().month) # 打印當前時間中的月份 4 print(datetime.datetime.now().day) # 打印當前時間中的天 23 print(datetime.datetime.now().hour) # 打印當前時間中的小時 9 print(datetime.datetime.now().minute) # 打印當前時間中的分鍾 33 print(datetime.datetime.now().second) # 打印當前時間中的秒 32 print(datetime.datetime.now().microsecond) # 打印當前時間中的毫秒 56063 print(datetime.datetime.now().strftime("%Y-%m-%d")) # 從時間格式轉換成字符串,滿足"%Y-%m-%d"格式的字符串格式 2018-04-23 09:33:32.055974 --> 2018-04-23 print(datetime.datetime.now().strftime("%c")) # 標准時間,類似於這種格式 Mon Apr 23 09:50:45 2018 print(datetime.datetime.now().strftime("%a")) # 本地簡化星期名稱 Mon print(datetime.datetime.now().strftime("%b")) # 本地簡化月份名稱 Apr print(datetime.datetime.now().strftime("%d")) # 當前這天是一個月中的第幾天 23 # 直接導入datetime模塊下面的datetime #from datetime import datetime #print(datetime.now())
%Y 帶世紀部分的十進制年份
%m 十進制表示的月份
%d 十進制表示的每月的第幾天
%H 24小時制的小時
%M 十進制表示的分鍾數
%S 十進制的秒數
如果我們需要表示昨天、上周等情況:
#!/usr/bin/env python from datetime import datetime from datetime import timedelta now_time = datetime.now() # 當前時間 print(now_time) b = now_time + timedelta(days = -1) # 一天前 print(b) c = now_time + timedelta(days = -1,weeks = -1) # 一個周前的前一天 print(c) 結果: 2018-04-23 10:35:40.245370 2018-04-22 10:35:40.245370 2018-04-15 10:35:40.245370
time模塊
這個time模塊不是datetime下面的那個模塊,它是一個單獨的模塊。
#!/usr/bin/env python import time time.sleep(2) # 暫停2秒后,打印 print("Hello") print(time.time()) # 打印時間戳,即從1970-01-01到現在的秒數 print(time.localtime()) # time.struct_time(tm_year=2018, tm_mon=4, tm_mday=23, tm_hour=10, tm_min=47, tm_sec=59, tm_wday=0, tm_yday=113, tm_isdst=0) time.strptime(string,[,format]) # 把一個格式化時間字符串轉化為struct_time,它和strftime是逆操作。
commands模塊
有時候我們需要使用shell命令,就用到了commands模塊。
#!/usr/bin/env python import commands output = commands.getoutput("ls -ll") # 返回執行完命令后的結果 print(output) status, output = commands.getstatusoutput("ls -l") # 返回一個元組,如果shell執行成功,第一個值(狀態碼)是0表示成功,第二個值是shell執行結果 print(status,output)
subprocess模塊
和commands模塊用法類似,都是用來執行shell命令的。
#!/usr/bin/env python from subprocess import PIPE,Popen p = Popen(['ifconfig'],stdout=PIPE) data = p.stdout.read() print(data)