1、模塊介紹
Python Module(模塊),就是一個保存了Python代碼的文件。模塊能定義函數,類和變量。模塊裏也能包含可執行的代碼。node
文件名就是模塊名加上後綴.py,在模塊內部,模塊名存儲在全局變量__name__中,是一個string,能夠直接在module中經過__name__引用到module name。python
模塊分爲三種:web
自定義模塊算法
內置標準模塊(又稱標準庫)shell
開源模塊編程
導入模塊:json
import: 使客戶端(導入者)以一個總體獲取一個模塊。bash
from:允許客戶端從一個模塊文件中獲取特定的變量名。數據結構
reload:在不停止Python程序的狀況下,提供了一個從新載入模塊文件代碼的方法。app
導入模塊方法:
1 語法: 2 import module 3 from module.xx.xx import xx 4 from module.xx.xx import xx as rename 5 from module.xx.xx import * #通常不推薦使用 6 7 8 示例: 9 10 推薦方法一: 11 12 import cal #當前目錄直接調用模塊 13 14 from my_module import cal #二層目錄調用模塊 15 16 from web1,web2,web3 import cal #多層目錄調用模塊 17 18 推薦方法二: 19 from web1,web2,web3.cal import add 20 21 22 注意:不支持的調用方式 23 from web1.web2 import web3 #執行__init__文件,惟一不支持的調用方式 24 print(web3.cal.add(2,6))
模塊路徑:
1 #獲取路徑 2 import sys 3 for i in sys.path: 4 print(i) 5 6 #輸出結果: 7 S:\Myproject 8 S:\Python 3.5.1\python35.zip 9 S:\Python 3.5.1\DLLs 10 S:\Python 3.5.1\lib #存放標準庫 11 S:\Python 3.5.1 12 S:\Python 3.5.1\lib\site-packages #存放第三方庫,擴充庫 13 14 #添加路徑 15 import os
16 pre_path = os.path.abspath('../') #當前路徑
17 import sys
18 sys.path.append(pre_path) #添加環境變量,臨時生效
19 環境變量:永久生效方法:個人電腦--->系統屬性--->環境變量--->Path路徑中添加,以";" 分割。
開源模塊:
1 #先安裝 gcc 編譯和 python 開發環境 2 yum install gcc 3 yum install python-devel 4 或 5 apt-get python-dev 6 7 #安裝方式(安裝成功後,模塊會自動安裝到 sys.path 中的某個目錄中) 8 yum 9 pip 10 apt-get 11 ... 12 #進入python環境,導入模塊檢查是否安裝成功
2、包(package)的概念
咱們先設想一下,若是不一樣的人編寫的模塊名相同怎麼辦?爲了不衝突,Python又引進了按目錄
來組織模塊的方法,稱爲包(package)。
假設,以下圖,個人兩個time_file.py模塊名字重名了,可是這兩個模塊的功能都不相同,若是這兩個模塊都在同一級目錄中,那麼我在其餘地方要調用這個time_file.py模塊,那麼這個時候就會發生衝突,在這裏咱們就能夠經過包來組織模塊,避免衝突,
方法是:選擇一個頂層包名,引入包之後,只要頂層的包名不與別人衝突,那這個包裏面的模塊都不會與別人衝突了。
請注意:每一個包目錄下來都會有一個__init__.py的文件,這個文件必須是存在的,不然,Python就不把這個目錄當成普通目錄,而不是一個包,__init__.py能夠是空文件,也能夠有python代碼,__init__.py自己就是一個文件,它的模塊命就是對應的包名,它通常因爲作接口文件。
3、time模塊
時間相關的操做,時間有三種表示方式: 時間戳 1970年1月1日以後的秒,即:time.time() 格式化的字符串 2016-12-12 10:10, 即:time.strftime('%Y-%m-%d') 結構化時間 元組 即:time.struct_time元組共有9個元素共九個元素:(年,月,日,時,分,秒,一年中第幾周,一年中第幾天,夏令時) 即:time.localtime()
1 import time 2 3 # 1 time() :返回當前時間的時間戳 4 time.time() #1473525444.037215 5 6 #---------------------------------------------------------- 7 8 # 2 localtime([secs]) 9 # 將一個時間戳轉換爲當前時區的struct_time。secs參數未提供,則以當前時間爲準。 10 time.localtime() #time.struct_time(tm_year=2016, tm_mon=9, tm_mday=11, tm_hour=0, 11 # tm_min=38, tm_sec=39, tm_wday=6, tm_yday=255, tm_isdst=0) 12 time.localtime(1473525444.037215) 13 14 #---------------------------------------------------------- 15 16 # 3 gmtime([secs]) 和localtime()方法相似,gmtime()方法是將一個時間戳轉換爲UTC時區(0時區)的struct_time。 17 18 #---------------------------------------------------------- 19 20 # 4 mktime(t) : 將一個struct_time轉化爲時間戳。 21 print(time.mktime(time.localtime()))#1473525749.0 22 23 #---------------------------------------------------------- 24 25 # 5 asctime([t]) : 把一個表示時間的元組或者struct_time表示爲這種形式:'Sun Jun 20 23:21:05 1993'。 26 # 若是沒有參數,將會將time.localtime()做爲參數傳入。 27 print(time.asctime())#Sun Sep 11 00:43:43 2016 28 29 #---------------------------------------------------------- 30 31 # 6 ctime([secs]) : 把一個時間戳(按秒計算的浮點數)轉化爲time.asctime()的形式。若是參數未給或者爲 32 # None的時候,將會默認time.time()爲參數。它的做用至關於time.asctime(time.localtime(secs))。 33 print(time.ctime()) # Sun Sep 11 00:46:38 2016 34 35 print(time.ctime(time.time())) # Sun Sep 11 00:46:38 2016 36 37 # 7 strftime(format[, t]) : 把一個表明時間的元組或者struct_time(如由time.localtime()和 38 # time.gmtime()返回)轉化爲格式化的時間字符串。若是t未指定,將傳入time.localtime()。若是元組中任何一個 39 # 元素越界,ValueError的錯誤將會被拋出。 40 print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56 41 42 # 8 time.strptime(string[, format]) 43 # 把一個格式化時間字符串轉化爲struct_time。實際上它和strftime()是逆操做。 44 print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X')) 45 46 #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6, 47 # tm_wday=3, tm_yday=125, tm_isdst=-1) 48 49 #在這個函數中,format默認爲:"%a %b %d %H:%M:%S %Y"。 50 51 52 # 9 sleep(secs) 53 # 線程推遲指定的時間運行,單位爲秒。 54 55 # 10 clock() 56 # 這個須要注意,在不一樣的系統上含義不一樣。在UNIX系統上,它返回的是「進程時間」,它是用秒錶示的浮點數(時間戳)。 57 # 而在WINDOWS中,第一次調用,返回的是進程運行的實際時間。而第二次以後的調用是自第一次調用之後到如今的運行 58 # 時間,即兩次時間差。
示例:
1 import time 2 3 print(time.time()) #1481556467.5820887 返回當前系統時間戳(1970年1月1日0時0分0秒開始) 4 5 print(time.localtime()) #將時間戳轉換爲struct_time格式,返回本地時間 6 #time.struct_time(tm_year=2016, tm_mon=12, tm_mday=12, tm_hour=23, tm_min=27, tm_sec=47, tm_wday=0, tm_yday=347, tm_isdst=0) 7 8 print(time.gmtime()) #將時間戳轉換爲struct_time格式 9 #time.struct_time(tm_year=2016, tm_mon=12, tm_mday=12, tm_hour=15, tm_min=27, tm_sec=47, tm_wday=0, tm_yday=347, tm_isdst=0) 10 11 print(time.mktime(time.localtime())) #1481556446.0 與time.localtime()功能相反,將struct_time格式轉回成時間戳格式 12 13 print(time.asctime()) #Mon Dec 12 23:26:24 2016 14 15 print(time.ctime()) #Mon Dec 12 23:26:24 2016 16 17 print(time.ctime(time.time())) #Mon Dec 12 23:26:24 2016 18 19 print(time.strftime("%Y-%m-%d %X",time.localtime())) #2016-12-12 23:26:24 20 21 print(time.strptime('2016-12-12 18:25:30','%Y-%m-%d %X')) #將字符串格式轉換成struct_time格式 22 #time.struct_time(tm_year=2016, tm_mon=12, tm_mday=12, tm_hour=18, tm_min=25, tm_sec=30, tm_wday=0, tm_yday=347, tm_isdst=-1) 23 24 #time.sleep(3) #sleep停頓3分鐘
查看幫助示例:
1 import time 2 help(time) 3 4 5 Help on built-in module time: 6 7 NAME 8 time - This module provides various functions to manipulate time values. 9 10 Commonly used format codes: 11 12 %Y Year with century as a decimal number. 13 %m Month as a decimal number [01,12]. 14 %d Day of the month as a decimal number [01,31]. 15 %H Hour (24-hour clock) as a decimal number [00,23]. 16 %M Minute as a decimal number [00,59]. 17 %S Second as a decimal number [00,61]. 18 %z Time zone offset from UTC. 19 %a Locale's abbreviated weekday name. 20 %A Locale's full weekday name. 21 %b Locale's abbreviated month name. 22 %B Locale's full month name. 23 %c Locale's appropriate date and time representation. 24 %I Hour (12-hour clock) as a decimal number [01,12]. 25 %p Locale's equivalent of either AM or PM. 26 27 28 import time 29 help(time.asctime) 30 31 Help on built-in function asctime in module time: 32 33 asctime(...) 34 asctime([tuple]) -> string 35 36 Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'. 37 When the time tuple is not present, current time as returned by localtime() 38 is used.
4、random 模塊
隨機數:
1 import random 2 3 print(random.random()) #用於生成一個0到1的隨機符點數: 0 <= n < 1.0 4 print(random.randint(1,2)) #用於生成一個指定範圍內的整數 5 print(random.randrange(1,10)) #從指定範圍內,按指定基數遞增的集合中獲取一個隨機數 6 print(random.uniform(1,10)) #用於生成一個指定範圍內的隨機符點數 7 print(random.choice('nick')) #從序列中獲取一個隨機元素 8 li = ['nick','jenny','car',] 9 random.shuffle(li) #用於將一個列表中的元素打亂 10 print(li) 11 li_new = random.sample(li,2) #從指定序列中隨機獲取指定長度的片段(從li中隨機獲取2個元素,做爲一個片段返回) 12 print(li_new)
驗證碼:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author: nulige 4 5 import random 6 7 def v_code(): 8 9 code = '' 10 for i in range(6): #生成隨機6位長度驗證碼,經過這裏控制 11 12 num=random.randint(0,9) 13 alf=chr(random.randint(65,90)) 14 add=random.choice([num,alf]) 15 code += str(add) 16 return code 17 18 print(v_code())
執行結果:
1 GAHTAR #隨機生成驗證碼(每次運行都不同)
5、os模塊
os模塊是與操做系統交互的一個接口
1 os.getcwd() 獲取當前工做目錄,即當前python腳本工做的目錄路徑 2 os.chdir("dirname") 改變當前腳本工做目錄;至關於shell下cd 3 os.curdir 返回當前目錄: ('.') 4 os.pardir 獲取當前目錄的父目錄字符串名:('..') 5 os.makedirs('dirname1/dirname2') 可生成多層遞歸目錄 6 os.removedirs('dirname1') 若目錄爲空,則刪除,並遞歸到上一級目錄,如若也爲空,則刪除,依此類推 7 os.mkdir('dirname') 生成單級目錄;至關於shell中mkdir dirname 8 os.rmdir('dirname') 刪除單級空目錄,若目錄不爲空則沒法刪除,報錯;至關於shell中rmdir dirname 9 os.listdir('dirname') 列出指定目錄下的全部文件和子目錄,包括隱藏文件,並以列表方式打印 10 os.remove() 刪除一個文件 11 os.rename("oldname","newname") 重命名文件/目錄 12 os.stat('path/filename') 獲取文件/目錄信息 13 os.sep 輸出操做系統特定的路徑分隔符,win下爲"\\",Linux下爲"/" 14 os.linesep 輸出當前平臺使用的行終止符,win下爲"\r\n",Linux下爲"\n" 15 os.pathsep 輸出用於分割文件路徑的字符串 win下爲;,Linux下爲: 16 os.name 輸出字符串指示當前使用平臺。win->'nt'; Linux->'posix' 17 os.system("bash command") 運行shell命令,直接顯示 18 os.environ 獲取系統環境變量 19 os.path.abspath(path) 返回path規範化的絕對路徑 20 os.path.split(path) 將path分割成目錄和文件名二元組返回 21 os.path.dirname(path) 返回path的目錄。其實就是os.path.split(path)的第一個元素 22 os.path.basename(path) 返回path最後的文件名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素 23 os.path.exists(path) 若是path存在,返回True;若是path不存在,返回False 24 os.path.isabs(path) 若是path是絕對路徑,返回True 25 os.path.isfile(path) 若是path是一個存在的文件,返回True。不然返回False 26 os.path.isdir(path) 若是path是一個存在的目錄,則返回True。不然返回False 27 os.path.join(path1[, path2[, ...]]) 將多個路徑組合後返回,第一個絕對路徑以前的參數將被忽略 28 os.path.getatime(path) 返回path所指向的文件或者目錄的最後存取時間 29 os.path.getmtime(path) 返回path所指向的文件或者目錄的最後修改時間
示例:
ps1: getcwd 獲取當前工做目錄 ,chdir("..") 改變當前腳本工做目錄
1 import os 2 3 print(os.getcwd()) #獲取當前工做目錄 4 os.chdir("..") #改變當前腳本工做目錄,至關於shell下cd 5 print(os.getcwd())
執行結果:
1 D:\python\day13 2 D:\python
ps2: makedirs 遞歸建立空目錄
1 import os 2 3 os.makedirs('dirname1/dirname2') #建立兩層空目錄
ps3: removedirs 若目錄爲空,則刪除,並遞歸到上一級目錄,如若也爲空,則刪除,依此類推
1 import os 2 3 os.removedirs("dirname1/dirname2")
ps4: listdir 列出指定目錄下的全部文件和子目錄,包括隱藏文件,並以列表方式打印
1 import os 2 3 print(os.listdir()) #顯示當前目錄下全部內容
ps5: stat 獲取文件/目錄信息
stat 結構:
1 import os 2 print(os.stat("json_s1.py"))
執行結果:
1 os.stat_result(st_mode=33206, st_ino=8162774324611606, st_dev=1753083748, st_nlink=1, st_uid=0, st_gid=0, st_size=464, st_atime=1481615313, st_mtime=1481615313, st_ctime=1481610945)
ps6: os.system(("dir")) 顯示目錄和文件
1 import os 2 print(os.system("dir")) #顯示目錄和文件
執行結果:
1 Volume in drive D is SSD 2 Volume Serial Number is 687D-EF64 3 4 Directory of D:\python\test 5 6 2016/12/27 15:39 <DIR> . 7 2016/12/27 15:39 <DIR> .. 8 2016/12/01 20:50 563 for.py 9 2016/12/09 08:20 21,892 haproxy01.py 10 2016/12/09 08:27 8,112 haproxy02.py 11 2016/12/24 23:10 16 hello 12 2016/12/27 15:39 258 os_module.py 13 2016/12/23 09:53 381 s1.py 14 2016/12/06 15:01 969 s2.py 15 2016/12/22 10:08 149 s4.py 16 2016/12/24 23:16 699 s5.py 17 2016/12/27 14:59 348 s6.py 18 2016/12/27 15:33 308 sys_module.py 19 2016/12/09 13:14 2,631 test.txt 20 12 File(s) 36,326 bytes 21 2 Dir(s) 639,014,264,832 bytes free
ps7: os.path.split 將文件分割成目錄和文件名
1 import os 2 print(os.path.split(r"C:\Users\Administrator\脫產三期\day22\sss.py")) #將path分割成目錄和文件名
執行結果:
1 ('C:\\Users\\Administrator\\脫產三期\\day22', 'sss.py')
ps8: os.path.dirname 返回path的目錄,加了r轉義
1 import os 2 print(os.path.dirname(r"C:\Users\Administrator\脫產三期\day22\sss.py")) #返回path的目錄。其實就是os.path.split(path)的第一個元素
執行結果:
1 C:\Users\Administrator\脫產三期\day22
ps9: 文件路徑的綜合應用
1 print(__file__) #獲取當前文件路徑的文件名 2 3 結果:D:/python/test/os_module.py 4 5 6 print(os.path.dirname(__file__)) #返回上一層目錄 7 8 結果:D:/python/test 9 10 11 print(os.path.abspath(__file__)) #返回他的絕對路徑 12 13 結果:D:\python\test\os_module.py 14 15 16 print(os.path.split(os.path.abspath(__file__))) #將path分割成目錄和文件名 17 18 結果:('D:\\python\\test', 'os_module.py') 19 20 print(os.path.dirname(os.path.abspath(__file__))) #返回當前文件的上一層目錄 21 22 結果:D:\python\test 23 24 print(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) #返回上二層的目錄 25 26 結果:D:\python
ps10: ps.path.hasename 返回path最後的文件名
1 import os 2 print(os.path.basename(r"C:\Users\Administrator\脫產三期\day22\sss.py")) #返回path最後的文件名。
執行結果:
1 sss.py
ps11: os.path.join 路徑拼接
ps1:
1 import os 2 a="D:\python\day13" 3 b="pickle_s1.py" 4 os.path.join(a,b)# 路徑拼接
執行結果:
1 C:\Python3.5\python.exe D:/python/day13/os_test.py
ps2: os.path.join 路徑和文件名拼接
1 print(os.path.join("d:\\")) 2 print(os.path.join("d:\\","www","baidu","test.py"))
執行結果:
1 d:\www\baidu\test.py
ps3: \test\bb\123.txt os.path.join拼接出這個路徑
1 print(os.path.join(os.path.dirname(os.path.abspath(__file__)),"bb","123.txt"))
執行結果:
1 D:\python\test\bb\123.txt #拼接出來的結果
6、sys模塊
1 sys.argv 命令行參數List,第一個元素是程序自己路徑 2 sys.exit(n) 退出程序,正常退出時exit(0) 3 sys.version 獲取Python解釋程序的版本信息 4 sys.maxint 最大的Int值 5 sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值 6 sys.platform 返回操做系統平臺名稱
一、sys.argv
1 import sys,os 2 3 li = sys.argv 4 5 if li[1] == "post": 6 print("post") 7 elif li[1] == "down": 8 print("11111")
需在終端執行,才能返回結果:
1 #用cd進入到python目錄 2 3 D:\python\test>python sys_module.py post 4 post #返回的結果 5 6 D:\python\test>python sys_module.py down 7 11111 #返回的結果
二、sys.path
1 import sys2 print(sys.path) 3 4 ps2: 5 for i in sys.path: 6 print(i)
執行結果:
1 ['D:\\python\\test', 'D:\\python', 'C:\\Python3.5\\python35.zip', 'C:\\Python3.5\\DLLs', 'C:\\Python3.5\\lib', 'C:\\Python3.5', 'C:\\Python3.5\\lib\\site-packages'] 2 D:\python\test 3 D:\python 4 C:\Python3.5\python35.zip 5 C:\Python3.5\DLLs 6 C:\Python3.5\lib 7 C:\Python3.5 8 C:\Python3.5\lib\site-packages
三、sys.version
1 print(sys.version)
執行結果:
1 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)]
四、進度條
1 import sys,time 2 for i in range(10): 3 sys.stdout.write('#') 4 time.sleep(1) 5 sys.stdout.flush()
7、json & pickle(* * * *)
用於序列化的兩個模塊
Json模塊提供了四個功能:dumps、dump、loads、load
pickle模塊提供了四個功能:dumps、dump、loads、load
dump()函數接受一個文件句柄和一個數據對象做爲參數,把數據對象以特定的格式保存 到給定的文件中。當咱們使用load()函數從文件中取出已保存的對象時,pickle知道如何恢復這些對象到它們原本的格式。
dumps()函數執行和dump() 函數相同的序列化。取代接受流對象並將序列化後的數據保存到磁盤文件,這個函數簡單的返回序列化的數據。
loads()函數執行和load() 函數同樣的反序列化。取代接受一個流對象並去文件讀取序列化後的數據,它接受包含序列化後的數據的str對象, 直接返回的對象。
示例:
ps1: 把一個字典,寫入到文件中
1 dic = '{"name": "alex"}' 2 f = open("hello", "w") 3 f.write(dic)
執行結果:
會生成一個hello文件
1 {"name": "alex"}
ps2: 讀取文件方法,把字典轉成字符串
1 f_read=open("hello","r") #讀取文件 2 data=f_read.read() 3 print(type(data)) 4 data=eval(data) #字典轉成字符串(eval的使用方法) 5 print(data["name"])
執行結果:
1 <class 'str'> 2 alex
json模塊方法:
ps1: 把字典轉換成json形式的字符串寫入文件中 (兩種方法效果同樣,只是寫法不一樣而已)
方法一:推薦用這種方法
1 #一、把字典轉換成json形式的字符串寫入文件中 2 import json 3 dic = {'name': 'alex'} 4 dic = json.dumps(dic) 5 f = open("hello", "w") 6 f.write(dic)
方法二:
1 import json 2 dic = {'name': 'alex'} 3 f = open("hello", "w") 4 dic = json.dump(dic, f)
執行結果:
會生成一個hello的文件,並寫入內容:
1 {"name": "alex"}
#----------------json------------------序列化(重點,必須掌握)
ps2: 把文件中json類型的字符串讀取出來轉換成字典
方法一:推薦用這種方法
1 #把文件中json類型的字符串讀取出來轉換成字典 2 import json 3 f = open('hello','r') 4 f = json.loads(f.read()) 5 print(f) 6 print(type(f))
方法二:
1 import json 2 f = open('hello','r') 3 f = json.load(f) #不經常使用這種方法 4 print(f) 5 print(type(f))
執行結果:
1 {'name': 'alex'} 2 <class 'dict'> #查看類型
注意知識點:
示例一:
1 import json 2 #dct="{'1':111}"#json 不認單引號 3 #dct=str({"1":111})#報錯,由於生成的數據仍是單引號:{'one': 1} 4 5 dct='{"1":"111"}' 6 print(json.loads(dct)) 7 8 #conclusion: 9 # 不管數據是怎樣建立的,只要知足json格式,就能夠json.loads出來,不必定非要dumps的數據才能loads
示例二:
先建立一個json_test文件,寫入內容
1 {"name":"alvin"} #只要符合json規範就能夠把值取出來。 另外一種示例:{'name':"alvin"} #若是是'name' 的值是單引號就會報錯。
再去取值
1 import json 2 3 with open("Json_test","r") as f: #雙引號能夠直接把值取出來 4 data=f.read() 5 data=json.loads(data) 6 print(data["name"])
執行結果:
1 alvin
json的dumps,loads,dump,load功能總結:
json.dumps(x) 把python的(x)原對象轉換成json字符串的對象,主要用來寫入文件。
json.loads(f) 把json字符串(f)對象轉換成python原對象,主要用來讀取文件和json字符串
json.dump(x,f) 把python的(x)原對象,f是文件對象,寫入到f文件裏面,主要用來寫入文件的
json.load(file) 把json字符串的文件對象,轉換成python的原對象,只是讀文件
pickle模塊:(不經常使用這個模塊)
#---------------pickle---------------序列化
ps1: pickle轉換後的結果是bytes(字節)
1 import pickle 2 3 dic = {'name': 'alvin', 'age': 23, 'sex': 'male'} 4 print(type(dic)) # <class 'dict'> 5 6 j = pickle.dumps(dic) 7 print(type(j)) # <class 'bytes'>
執行結果:
1 <class 'dict'> #字典類型 2 <class 'bytes'> #bytes類型
ps2:
1 import pickle 2 3 dic = {'name': 'alvin', 'age': 23, 'sex': 'male'} 4 j = pickle.dumps(dic) 5 f = open('序列化對象_pickle', 'wb') #注意是w是寫入str,wb是寫入bytes,j是'bytes' 6 f.write(j) #等價於pickle.dump(dic,f) 7 f.close()
執行結果:
生成一個序列化對象_pickle文件,文件內容以下:
1 �}q (X ageqKX sexqX maleqX nameqX alvinqu. #生成一個不可讀的文件,但計算機能夠解析出來
ps3: 反序列化
1 import pickle 2 3 f = open('序列化對象_pickle', 'rb') 4 data = pickle.loads(f.read()) # 等價於data=pickle.load(f) 5 print(data['age'])
執行結果:
1 23 #讀出裏面的結果
Pickle的問題和全部其餘編程語言特有的序列化問題同樣,就是它只能用於Python,而且可能不一樣版本的Python彼此都不兼容,所以,只能用Pickle保存那些不重要的數據,不能成功地反序列化也不要緊。
8、shelve模塊
shelve模塊比pickle模塊簡單,只有一個open函數,返回相似字典的對象,可讀可寫;key必須爲字符串,而值能夠是python所支持的數據類型
ps1:
1 #添加鍵值對到文件中,會生成三個文件,並寫入字典內容 2 3 import shelve 4 5 f = shelve.open(r'shelve1') # 目的:將一個字典放入文本 f={} 6 f['stu1_info']={'name':'alex','age':'18'} 7 f['stu2_info']={'name':'alvin','age':'20'} 8 f['school_info']={'website':'oldboyedu.com','city':'beijing'} 9 f.close()
執行結果:
會生成三個文件:shelvel.dat,shelve1.dir,shelve1.bak,其中shelvel.bak中內容以下:
1 'stu1_info', (0, 49) #生成只有計算機能識別的語言 2 'stu2_info', (512, 50) 3 'school_info', (1024, 67)
ps2:取出age的值
1 import shelve 2 3 f = shelve.open(r'shelve1') 4 print(f.get('stu1_info')['age']) #取出age的值 5 print(f.get('stu2_info')['age'])
執行結果:
1 18 2 20
9、xml模塊
xml是實現不一樣語言或程序之間進行數據交換的協議,跟json差很少,但json使用起來更簡單,不過,古時候,在json還沒誕生的黑暗年代,你們只能選擇用xml呀,至今不少傳統公司如金融行業的不少系統的接口還主要是xml。
xml的格式以下,就是經過<>節點來區別數據結構的:
1 <?xml version="1.0"?> 2 <data> #根 3 <country name="Liechtenstein"> #節點 4 <rank updated="yes">2</rank> 5 <year>2008</year> 6 <gdppc>141100</gdppc> 7 <neighbor name="Austria" direction="E"/> 8 <neighbor name="Switzerland" direction="W"/> 9 </country> 10 <country name="Singapore"> #節點 11 <rank updated="yes">5</rank> 12 <year>2011</year> 13 <gdppc>59900</gdppc> 14 <neighbor name="Malaysia" direction="N"/> 15 </country> 16 <country name="Panama"> #節點 17 <rank updated="yes">69</rank> 18 <year>2011</year> 19 <gdppc>13600</gdppc> 20 <neighbor name="Costa Rica" direction="W"/> 21 <neighbor name="Colombia" direction="E"/> 22 </country> 23 </data> 24 25 xml數據
xml協議在各個語言裏的都 是支持的,在python中能夠用如下模塊操做xml:
1 import xml.etree.ElementTree as ET 2 3 tree = ET.parse("xmltest.xml") 4 root = tree.getroot() 5 print(root.tag) 6 7 #遍歷xml文檔 8 for child in root: 9 print(child.tag, child.attrib) 10 for i in child: 11 print(i.tag,i.text) 12 13 #只遍歷year 節點 14 for node in root.iter('year'): 15 print(node.tag,node.text)
#執行結果:
year 2008
year 2011
year 2011 16 #--------------------------------------- 17 18 import xml.etree.ElementTree as ET 19 20 tree = ET.parse("xmltest.xml") 21 root = tree.getroot() 22 23 #修改 24 for node in root.iter('year'): 25 new_year = int(node.text) + 1 #2008+1=2009 26 node.text = str(new_year) 27 node.set("updated","yes") #修改經過set,加個屬性yes 28 29 tree.write("xmltest.xml") 30 31 #執行結果:
會生成一個新的xmltest.xml文件,內容中會添加
<year updated="yes">2009</year> #年份+1,加個yes屬性
32 #刪除node 33 for country in root.findall('country'): #經過對country進行遍歷 34 rank = int(country.find('rank').text) #再用find找到rank 35 if rank > 50: #再判斷>50的值 36 root.remove(country) #再用remove刪除 37 38 tree.write('output.xml') #寫到一個新文件中
#執行結果:
本身建立xml文檔:
1 import xml.etree.ElementTree as ET #as後面的ET是前面的類的別名,名稱隨便取 2 3 4 new_xml = ET.Element("namelist") 5 name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"}) 6 age = ET.SubElement(name,"age",attrib={"checked":"no"}) 7 sex = ET.SubElement(name,"sex") 8 sex.text = '33' 9 name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"}) 10 age = ET.SubElement(name2,"age") 11 age.text = '19' 12 13 et = ET.ElementTree(new_xml) #生成文檔對象 (記住重點) 14 et.write("test.xml", encoding="utf-8",xml_declaration=True) (記住重點) 15 16 ET.dump(new_xml) #打印生成的格式 17 18 建立xml文檔
執行結果:
會生成一個test.xml的文件,文件內容以下:
1 <?xml version='1.0' encoding='utf-8'?> 2 3 <namelist> 4 <name enrolled="yes"> 5 <age checked="no" /> 6 <sex>33</sex> 7 </name> 8 <name enrolled="no"> 9 <age>19</age> 10 </name> 11 </namelist>
10、configparser 模塊
configparser 模塊做用: 用來讀寫配置文件。
1、常見文檔格式以下:
一、先新建一個名字爲confile文件,寫入下面內容:
1 [DEFAULT] 2 ServerAliveInterval = 45 3 Compression = yes 4 CompressionLevel = 9 5 ForwardX11 = yes 6 7 [bitbucket.org] 8 User = hg 9 10 [topsecret.server.com] 11 Port = 50022 12 ForwardX11 = no
示例1: 寫入一個文件
1 import configparser 2 3 config = configparser.ConfigParser() #config={} 4 5 config["DEFAULT"] = {'ServerAliveInterval': '45', 6 'Compression': 'yes', 7 'CompressionLevel': '9'} 8 9 with open('example1.ini', 'w') as f: 10 config.write(f)
執行結果:
1 #會生成example1.ini文件,內容以下: 2 [DEFAULT] 3 compressionlevel = 9 4 compression = yes 5 serveraliveinterval = 45
示例2: 生成多個鍵值對
1 import configparser 2 3 config = configparser.ConfigParser() #config={} 4 5 config["DEFAULT"] = {'ServerAliveInterval': '45', 6 'Compression': 'yes', 7 'CompressionLevel': '9'} 8 9 config['bitbucket.org'] = {} 10 config['bitbucket.org']['User'] = 'hg' 11 12 config['topsecret.server.com'] = {} 13 topsecret = config['topsecret.server.com'] 14 topsecret['Host Port'] = '50022' # mutates the parser 15 topsecret['ForwardX11'] = 'no' # same here 16 17 with open('example1.ini', 'w') as f: 18 config.write(f)
執行結果:
#會生成example1.ini文件,內容以下: [DEFAULT] compression = yes compressionlevel = 9 serveraliveinterval = 45 [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no
#-----------------------------------查詢功能-------------------------------#
示例3: 實現查詢功能
#查出鍵中user對應的值
1 import configparser 2 3 config = configparser.ConfigParser() 4 config.read('example1.ini') #先把文件讀進來 5 print(config['bitbucket.org']['User']) #取出user的值 6 print(config['DEFAULT']['Compression']) #Compression的值 7 print(config['topsecret.server.com']['ForwardX11']) #ForwardX11的值
執行結果:
1 hg 2 yes 3 no
示例4:取的是bitbucket.org鍵的值,他會把DEFAULT的一塊兒打印出來
DEFAULT的特殊功能:由於只要帶DEFAULT鍵值對的,他就會把DEFAULT的鍵打印出來
1 import configparser 2 3 config = configparser.ConfigParser() 4 config.read('example1.ini') 5 6 for key in config['bitbucket.org']: #取的是bitbucket.org的值,他會把DEFAULT的一塊兒打印出來 7 print(key)
執行結果:
1 user 2 compression 3 compressionlevel 4 serveraliveinterval
示例5:
取的是bitbucket.org鍵的值,以列表的方式打印出來
1 import configparser 2 3 config = configparser.ConfigParser() 4 config.read('example1.ini') 5 print(config.options('bitbucket.org'))
執行結果:
1 ['user', 'compression', 'compressionlevel', 'serveraliveinterval']
示例6:
取的是bitbucket.org鍵和值,以元組的方式打印出來
1 import configparser 2 3 config = configparser.ConfigParser() 4 config.read('example1.ini') 5 print(config.items('bitbucket.org'))
執行結果:
1 [('compression', 'yes'), ('compressionlevel', '9'), ('serveraliveinterval', '45'), ('user', 'hg')]
示例7:
連續取值,取出compression的值
1 import configparser 2 3 config = configparser.ConfigParser() 4 config.read('example1.ini') 5 6 print(config.get('bitbucket.org','compression')) #取出compression的值
執行結果:
1 yes #=====>取出的compression的值 yes
#-------------------------------------增長功能----------------------------------#
實現:在example1.txt文件中讀取原來塊的內容,增長一個新的塊
一、首先必須有一個example1.txt文件,裏面內容爲:
1 [DEFAULT] 2 serveraliveinterval = 45 3 compression = yes 4 compressionlevel = 9 5 6 [bitbucket.org] 7 user = hg 8 9 [topsecret.server.com] 10 host port = 50022 11 forwardx11 = no
二、增長一個塊和鍵值對
1 import configparser 2 3 config = configparser.ConfigParser() 4 config.read('example1.ini') #從這裏面拿到三個對象 5 6 config.add_section('yuan') #再新增長一個塊 7 config.set('yuan','k1','11111') #給鍵添加鍵值對 8 config.write(open('1.cfg', "w")) #建立一個新文件
執行結果:
1 [DEFAULT] 2 serveraliveinterval = 45 3 compression = yes 4 compressionlevel = 9 5 6 [bitbucket.org] 7 user = hg 8 9 [topsecret.server.com] 10 host port = 50022 11 forwardx11 = no 12 13 [yuan] #這就是新增長的塊 14 k1 = 11111
#-------------------------------------刪除功能----------------------------------#
示例1:
一、首先必須有一個example1.txt文件,裏面內容爲:
1 [DEFAULT] 2 serveraliveinterval = 45 3 compression = yes 4 compressionlevel = 9 5 6 [bitbucket.org] 7 user = hg 8 9 [topsecret.server.com] 10 host port = 50022 11 forwardx11 = no 12 13 [yuan] #這就是新增長的塊 14 k1 = 11111
二、刪除塊和鍵值對的值
1 import configparser 2 3 config = configparser.ConfigParser() 4 config.read('example1.ini') #從這裏面拿到三個對象 5 6 config.remove_section('topsecret.server.com') #刪除塊和鍵值對的值 7 config.remove_option('bitbucket.org','user') 8 config.write(open('1.cfg', "w")) #建立一個新文件
執行結果:
1 [DEFAULT] 2 serveraliveinterval = 45 3 compression = yes 4 compressionlevel = 9 5 6 [bitbucket.org]
11、logging模塊
1、logging模塊
示例1:
1 import logging 2 3 logging.debug('debug message') 4 logging.info('info message') 5 logging.warning('warning message') 6 logging.error('error message') 7 logging.critical('critical message')
執行結果: (默認是WARNING級別,因此只顯示三條信息)
1 WARNING:root:warning message 2 ERROR:root:error message 3 CRITICAL:root:critical message
日誌級別:通常info就夠用
默認狀況下Python的logging模塊將日誌打印到了標準輸出中,且只顯示了大於等於WARNING級別的日誌,這說明默認的日誌級別設置爲WARNING
日誌級別等級CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET(從高到低),默認的日誌格式爲日誌級別:Logger名稱:用戶輸出消息。
示例2: 設置參數,調日誌級別。調整爲DEBUG級別,顯示5條信息
1 import logging 2 3 logging.basicConfig( 4 level=logging.DEBUG 5 ) 6 7 logging.debug('debug message') 8 logging.info('info message') 9 logging.warning('warning message') 10 logging.error('error message') 11 logging.critical('critical message')
執行結果: 顯示5條信息
1 DEBUG:root:debug message 2 INFO:root:info message 3 WARNING:root:warning message 4 ERROR:root:error message 5 CRITICAL:root:critical message
示例3: 設置filename把日誌寫入到文件中,並參過加w參數,控制他每次只寫5條,不重複的記錄
1 import logging 2 3 logging.basicConfig( 4 level=logging.DEBUG, #默認信息顯示在屏幕上面 5 filename="logger.log", #經過加filename參數,以追加的方式,把日誌信息寫入到文件中,每次重複運行都會往裏面寫5條記錄 6 filemode="w", #經過加w參數,就能夠控制他,每次只寫5條記錄。不會重複往裏寫相同記錄 7 ) 8 9 logging.debug('debug message') 10 logging.info('info message') 11 logging.warning('warning message') 12 logging.error('error message') 13 logging.critical('critical message')
執行結果:
1 會建立一個logger.log日誌,並寫入五條記錄 2 DEBUG:root:debug message 3 INFO:root:info message 4 WARNING:root:warning message 5 ERROR:root:error message 6 CRITICAL:root:critical message
示例4: 給logging加上參數,顯示時間,行號等信息。
1 import logging 2 3 logging.basicConfig( 4 level=logging.DEBUG, #默認信息顯示在屏幕上面 5 filename="logger.log", #經過加filename參數,以追加的方式,把日誌信息寫入到文件中,每次重複運行都會往裏面寫5條記錄 6 filemode="w", #經過加w參數,就能夠控制他,每次只寫5條記錄。不會重複往裏寫相同記錄 7 # format="%(asctime)s", #加上時間 8 format="%(asctime)s %(filename)s[%(lineno)d] %(message)s" #asctime 時間,lineno 行號,message 信息,還能夠加其它信息參數 9 ) 10 11 logging.debug('debug message') 12 logging.info('info message') 13 logging.warning('warning message') 14 logging.error('error message') 15 logging.critical('critical message')
執行結果:
1 會建立一個logger.log日誌,並寫入五條記錄 2 2016-12-15 14:10:33,615 logging_s1.py[15] debug message 3 2016-12-15 14:10:33,616 logging_s1.py[16] info message 4 2016-12-15 14:10:33,616 logging_s1.py[17] warning message 5 2016-12-15 14:10:33,616 logging_s1.py[18] error message 6 2016-12-15 14:10:33,617 logging_s1.py[19] critical message
可見在logging.basicConfig()函數中可經過具體參數來更改logging模塊默認行爲,可用參數有
filename:用指定的文件名建立FiledHandler(後邊會具體講解handler的概念),這樣日誌會被存儲在指定的文件中。
filemode:文件打開方式,在指定了filename時使用這個參數,默認值爲「a」還可指定爲「w」。
format:指定handler使用的日誌顯示格式。
datefmt:指定日期時間格式。
level:設置rootlogger(後邊會講解具體概念)的日誌級別
stream:用指定的stream建立StreamHandler。能夠指定輸出到sys.stderr,sys.stdout或者文件(f=open('test.log','w')),默認爲sys.stderr。若同時列出了filename和stream兩個參數,則stream參數會被忽略。
format參數中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 數字形式的日誌級別
%(levelname)s 文本形式的日誌級別
%(pathname)s 調用日誌輸出函數的模塊的完整路徑名,可能沒有
%(filename)s 調用日誌輸出函數的模塊的文件名
%(module)s 調用日誌輸出函數的模塊名
%(funcName)s 調用日誌輸出函數的函數名
%(lineno)d 調用日誌輸出函數的語句所在的代碼行
%(created)f 當前時間,用UNIX標準的表示時間的浮 點數表示
%(relativeCreated)d 輸出日誌信息時的,自Logger建立以 來的毫秒數
%(asctime)s 字符串形式的當前時間。默認格式是 「2003-07-08 16:49:45,896」。逗號後面的是毫秒
%(thread)d 線程ID。可能沒有
%(threadName)s 線程名。可能沒有
%(process)d 進程ID。可能沒有
%(message)s用戶輸出的消息
2、logger對象(自定義日誌格式,常常用的一種方法) 重點掌握
上述幾個例子中咱們瞭解到了logging.debug()、logging.info()、logging.warning()、logging.error()、logging.critical()(分別用以記錄不一樣級別的日誌信息),logging.basicConfig()(用默認日誌格式
(Formatter)爲日誌系統創建一個默認的流處理器(StreamHandler),設置基礎配置(如日誌級別等)並加到root logger(根Logger)中)這幾個logging模塊級別的函數,另外還有一個模塊級別的函數
是logging.getLogger([name])(返回一個logger對象,若是沒有指定名字將返回root logger)
原理圖:
示例1:
1 import logging 2 3 logger=logging.getLogger() #建立一個大對象 4 5 fh=logging.FileHandler("test_log") #向文件裏發送內容,而且給個參數,做用是:定義一個文件名,往文件裏寫入內容 6 ch=logging.StreamHandler() #向屏幕上發送內容 7 8 fm=logging.Formatter("%(asctime)s %(message)s") #這個也是一個對象,做用是:定義日誌格式 9 10 fh.setFormatter(fm) #往文件裏寫內容 11 ch.setFormatter(fm) #往屏幕上輸出內容 12 13 logger.addHandler(fh) #對象,相似於吸別人內力,把fh吃掉 14 logger.addHandler(ch) #對象,相似於吸別人內力,把ch吃掉 15 16 logger.debug("debug") #輸出日誌的級別 17 logger.info("info") 18 logger.warning("warning") 19 logger.error("error") 20 logger.critical("critical")
執行結果:
1 會生成一個test_log的文件,同時往裏面寫入信息,並在屏幕上面顯示相同信息。 2 文件內容以下: 3 2016-12-15 14:38:27,657 warning 4 2016-12-15 14:38:27,658 error 5 2016-12-15 14:38:27,658 critical 6 7 屏幕輸出信息以下: 8 2016-12-15 14:38:27,657 warning 9 2016-12-15 14:38:27,658 error 10 2016-12-15 14:38:27,658 critical
示例2: logger.setLevel("DEBUG") 調整日誌級別,控制日誌顯示信息,DEBUG顯示5條記錄
1 import logging 2 3 logger=logging.getLogger() #建立一個大對象 4 5 fh=logging.FileHandler("test_log") #向文件裏發送內容,而且給個參數,做用是:定義一個文件名,往文件裏寫入內容 6 ch=logging.StreamHandler() #向屏幕上發送內容 7 8 fm=logging.Formatter("%(asctime)s %(message)s") #這個也是一個對象,做用是:定義日誌格式 9 10 fh.setFormatter(fm) #往文件裏寫內容 11 ch.setFormatter(fm) #往屏幕上輸出內容 12 13 logger.addHandler(fh) #對象,相似於吸別人內力,把fh吃掉 14 logger.addHandler(ch) #對象,相似於吸別人內力,把ch吃掉 15 logger.setLevel("DEBUG") #設置日誌級別,控制日誌輸入多少條信息 16 17 18 #-------------從這裏開始都是在操做log---------------- 19 20 logger.debug("debug") #輸出日誌的級別 21 logger.info("info") 22 logger.warning("warning") 23 logger.error("error") 24 logger.critical("critical")
執行結果:
1 會生成一個test_log的文件,同時往裏面寫入信息,並在屏幕上面顯示相同信息。 2 文件內容以下: 3 2016-12-15 14:54:37,036 debug 4 2016-12-15 14:54:37,037 info 5 2016-12-15 14:54:37,038 warning 6 2016-12-15 14:54:37,038 error 7 2016-12-15 14:54:37,039 critical 8 9 屏幕輸出信息以下: 10 2016-12-15 14:54:37,036 debug 11 2016-12-15 14:54:37,037 info 12 2016-12-15 14:54:37,038 warning 13 2016-12-15 14:54:37,038 error 14 2016-12-15 14:54:37,039 critical
示例3: 寫成函數的形式,並有返回值
1 import logging 2 3 def logger(): 4 5 logger=logging.getLogger() #建立一個大對象 6 7 fh=logging.FileHandler("test_log") #向文件裏發送內容,而且給個參數,做用是:定義一個文件名,往文件裏寫入內容 8 ch=logging.StreamHandler() #向屏幕上發送內容 9 10 fm=logging.Formatter("%(asctime)s %(message)s") #這個也是一個對象,做用是:定義日誌格式 11 12 fh.setFormatter(fm) #往文件裏寫內容 13 ch.setFormatter(fm) #往屏幕上輸出內容 14 15 logger.addHandler(fh) #對象,相似於吸別人內力,把fh吃掉 16 logger.addHandler(ch) #對象,相似於吸別人內力,把ch吃掉 17 logger.setLevel("DEBUG") #設置日誌級別,控制日誌輸入多少條信息 18 19 return logger 20 21 #-------------從這裏開始都是在操做log---------------- 22 logger=logger() #這個日誌就作成了一個接口,想在其它地方使用,直接調用他就能夠啦! 23 24 logger.debug("debug") #輸出日誌的級別 25 logger.info("info") 26 logger.warning("warning") 27 logger.error("error") 28 logger.critical("critical")
執行結果:
1 會生成一個test_log的文件,同時往裏面寫入信息,並在屏幕上面顯示相同信息。 2 文件內容以下: 3 2016-12-15 14:54:37,036 debug 4 2016-12-15 14:54:37,037 info 5 2016-12-15 14:54:37,038 warning 6 2016-12-15 14:54:37,038 error 7 2016-12-15 14:54:37,039 critical 8 9 屏幕輸出信息以下: 10 2016-12-15 14:54:37,036 debug 11 2016-12-15 14:54:37,037 info 12 2016-12-15 14:54:37,038 warning 13 2016-12-15 14:54:37,038 error 14 2016-12-15 14:54:37,039 critical
示例4: 只在屏幕文件中寫入日誌,不在屏幕上面顯示
1 import logging 2 3 def logger(): 4 5 logger=logging.getLogger() #建立一個大對象 6 7 fh=logging.FileHandler("test_log") #向文件裏發送內容,而且給個參數,做用是:定義一個文件名,往文件裏寫入內容 8 #ch=logging.StreamHandler() #向屏幕上發送內容 9 10 fm=logging.Formatter("%(asctime)s %(message)s") #這個也是一個對象,做用是:定義日誌格式 11 12 fh.setFormatter(fm) #往文件裏寫內容 13 #ch.setFormatter(fm) #往屏幕上輸出內容 14 15 logger.addHandler(fh) #對象,相似於吸別人內力,把fh吃掉 16 #logger.addHandler(ch) #對象,相似於吸別人內力,把ch吃掉 17 logger.setLevel("DEBUG") #設置日誌級別,控制日誌輸入多少條信息 18 19 return logger 20 21 #-------------從這裏開始都是在操做log---------------- 22 logger=logger() #這個日誌就作成了一個接口,在其它地方,直接調用他就能夠啦! 23 24 logger.debug("debug") #輸出日誌的級別 25 logger.info("info") 26 logger.warning("warning") 27 logger.error("error") 28 logger.critical("critical")
執行結果:
1 #會生成一個test_log的文件,同時往裏面寫入信息,不會在屏幕上面顯示信息。 2 #文件內容以下: 3 2016-12-15 14:54:37,036 debug 4 2016-12-15 14:54:37,037 info 5 2016-12-15 14:54:37,038 warning 6 2016-12-15 14:54:37,038 error 7 2016-12-15 14:54:37,039 critical
示例5:沒有根用戶
#若是咱們再建立兩個logger對象
1 import logging 2 3 logger1 = logging.getLogger('mylogger') #默認是根,這裏表明他是子用戶(兩個用戶是同級) 4 #logger1 = logging.getLogger('mylogger.sontree') #若是mylogger下再建立一個字對象,就用.sontree;等於他就是mylogger的下級對象。 5 logger1.setLevel(logging.DEBUG) #第一次是DEBUG級別 6 7 logger2 = logging.getLogger('mylogger') #默認是根,這裏表明他是子用戶(兩個用戶是同級) 8 logger2.setLevel(logging.INFO) #第二次是INFO級別,覆蓋第一次的級別,因此打印結果是INFO級別顯示 9 10 fh=logging.FileHandler("test_log-new") #向文件裏發送內容,而且給個參數,做用是:定義一個文件名,往文件裏寫入內容 11 ch=logging.StreamHandler() #向屏幕上發送內容 12 13 logger1.addHandler(fh) 14 logger1.addHandler(ch) 15 16 logger2.addHandler(fh) 17 logger2.addHandler(ch)
執行結果:
1 logger1 and logger2各打印4條信息 2 生成一個test_log-new的文件,同時往裏面寫入信息,並在屏幕上面顯示相同信息。 3 文件內容以下: 4 logger1 info message 5 logger1 warning message 6 logger1 error message 7 logger1 critical message 8 logger2 info message 9 logger2 warning message 10 logger2 error message 11 logger2 critical message 12 13 #屏幕上面顯示的內容 14 logger1 info message 15 logger1 warning message 16 logger1 error message 17 logger1 critical message 18 logger2 info message 19 logger2 warning message 20 logger2 error message 21 logger2 critical message
示例6:添加根用戶 (lgger和mylogger是父子關係) (注意日誌輸出問題)
1 import logging 2 3 logger = logging.getLogger() #根用戶(根用戶級別,沒有定義日誌級別,默認warning級別,因此是3條信息 4 5 logger1 = logging.getLogger('mylogger') #默認是根,這裏表明他是子用戶(兩個用戶是同級) 6 logger1.setLevel(logging.DEBUG) #第一次是DEBUG級別,默認是打印五條信息,可是他打印信息的時候,會先去找父,若是有父,他就會多打印一遍,因此輸出是10條信息 7 8 fh=logging.FileHandler("test_log-new") #向文件裏發送內容,而且給個參數,做用是:定義一個文件名,往文件裏寫入內容 9 ch=logging.StreamHandler() #向屏幕上發送內容 10 11 logger.addHandler(ch) #添加一個根用戶 12 logger.addHandler(fh) 13 14 logger1.addHandler(fh) #添加一個子用戶 15 logger1.addHandler(ch) 16 17 #打印信息 18 logger.debug('logger debug message') 19 logger.info('logger info message') 20 logger.warning('logger warning message') 21 logger.error('logger error message') 22 logger.critical('logger critical message') 23 24 #打印4條信息 25 logger1.debug('logger1 debug message') 26 logger1.info('logger1 info message') 27 logger1.warning('logger1 warning message') 28 logger1.error('logger1 error message') 29 logger1.critical('logger1 critical message')
輸出結果:
1 生成一個test_log-new的文件,同時往裏面寫入信息,並在屏幕上面顯示相同信息。 2 文件內容以下: 3 logger warning message 4 logger error message 5 logger critical message #前三條是根輸出的三條信息 6 logger1 debug message #後10條是子輸出的10條信息,爲何會輸入10條呢? 7 logger1 debug message #第一次是DEBUG級別,默認是打印五條信息,可是他打印信息的時候,會先去找父,若是有父,他就會多打印一遍,因此輸出是5+5=10條信息 8 logger1 info message 9 logger1 info message 10 logger1 warning message 11 logger1 warning message 12 logger1 error message 13 logger1 error message 14 logger1 critical message 15 logger1 critical message 16 17 屏幕輸出內容以下: 18 logger warning message 19 logger error message 20 logger critical message 21 logger1 debug message 22 logger1 debug message 23 logger1 info message 24 logger1 info message 25 logger1 warning message 26 logger1 warning message 27 logger1 error message 28 logger1 error message 29 logger1 critical message 30 logger1 critical message
示例7:添加根用戶 (控制根用戶不輸入,只輸出子用戶信息)
1 import logging 2 3 logger = logging.getLogger() #根用戶(根用戶級別,沒有定義日誌級別,默認warning級別,因此是3條信息 4 5 logger1 = logging.getLogger('mylogger') #默認是根,這裏表明他是子用戶(兩個用戶是同級) 6 logger1.setLevel(logging.DEBUG) #第一次是DEBUG級別,默認是打印五條信息,可是他打印信息的時候,會先去找父,若是有父,他就會多打印一遍,因此輸出是10條信息 7 8 fh=logging.FileHandler("test_log-new") #向文件裏發送內容,而且給個參數,做用是:定義一個文件名,往文件裏寫入內容 9 ch=logging.StreamHandler() #向屏幕上發送內容 10 11 logger1.addHandler(fh) #添加一個子用戶 12 logger1.addHandler(ch) 13 14 #打印4條信息 15 logger1.debug('logger1 debug message') 16 logger1.info('logger1 info message') 17 logger1.warning('logger1 warning message') 18 logger1.error('logger1 error message') 19 logger1.critical('logger1 critical message')
執行結果:
#生成一個test_log-new的文件,同時往裏面寫入信息,並在屏幕上面顯示相同信息。 文件內容以下: logger1 debug message logger1 info message logger1 warning message logger1 error message logger1 critical message 屏幕輸出內容以下: logger1 debug message logger1 info message logger1 warning message logger1 error message logger1 critical message
12、hashlib模塊 (摘要算法)
hashlib 明文變成密文,不能反解
用於加密相關的操做,3.x裏代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
md5算法 明文變成密文
示例1: md5算法
1 import hashlib 2 3 obj=hashlib.md5() 4 obj.update("admin".encode("utf8")) 5 print(obj.hexdigest())
執行結果:
1 21232f297a57a5a743894a0e4a801fc3 (長度32位)
示例2:
1 import hashlib 2 3 #md5加密+字符串,生成密碼。就沒法破解 4 obj=hashlib.md5("sssdsdsb".encode("utf8")) #在md5裏面加點字符串,再生成,就無法破解 5 obj.update("admin".encode("utf8")) 6 7 print(obj.hexdigest())
執行結果:
1 639cd764cf1bab2bebaa5804e37530e6
示例3:
以上加密算法雖然依然很是厲害,但時候存在缺陷,即:經過撞庫能夠反解。因此,有必要對加密算法中添加自定義key再來作加密。
####### 256 位########
1 import hashlib 2 3 hash = hashlib.sha256('898oaFs09f'.encode('utf8')) 4 hash.update('alvin'.encode('utf8')) 5 print(hash.hexdigest())
執行結果:
1 e79e68f070cdedcfe63eaf1a2e92c83b4cfb1b5c6bc452d214c1b7e77cdfd1c7
示例4:
python 還有一個 hmac 模塊,它內部對咱們建立 key 和 內容 再進行處理而後再加密:
1 import hmac 2 3 h = hmac.new('alvin'.encode('utf8')) 4 h.update('hello'.encode('utf8')) 5 print (h.hexdigest())
執行結果:
1 320df9832eab4c038b6c1d7ed73a5940