Python學習——python的常用模塊


模塊:用一堆代碼實現了某個功能的代碼集合,模塊是不帶 .py 擴展的另外一個 Python 文件的文件名。

一、time & datetime模塊

 1 import time
 2 import datetime
 3 
 4 print(time.asctime())      # 返回時間格式:Sun May  7 21:46:15 2017
 5 print(time.time())         # 返回時間戳 ‘1494164954.6677325’
 6 print(time.gmtime())       # 返回本地時間 的struct time對象格式,time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=22, tm_min=4, tm_sec=53, tm_wday=6, tm_yday=127, tm_isdst=0)
 7 print(time.localtime())    # 返回本地時間 的struct time對象格式,time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=22, tm_min=4, tm_sec=53, tm_wday=6, tm_yday=127, tm_isdst=0)
 8 print(time.gmtime(time.time()-800000))   # 返回utc時間的struc時間對象格式
 9 print(time.asctime(time.localtime()))    # 返回時間格式Sun May  7 22:15:09 2017
10 print(time.ctime())                      # 返回時間格式Sun May  7 22:15:09 2017
11 print(time.strftime('%Y-%m-%d'))         #默認當前時間 2017-05-07
12 print(time.strftime('%Y-%m-%d',time.localtime())) #默認當前時間 2017-05-07
13 
14 string_struct = time.strptime("2016/05/22","%Y/%m/%d") # 將日期字符串 轉成 struct時間對象格式
15 print(string_struct)                     # 返回struct time對象格式 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=143, tm_isdst=-1)
16 
17 # 將日期字符串轉成時間戳
18 struct_stamp = time.mktime(string_struct) # 將struct time時間對象轉成時間戳
19 print(struct_stamp)                         # 返回時間戳 ‘1463846400.0’
20 
21 # 將時間戳轉為字符串格式
22 print(time.gmtime(time.time()-86640))         # 將utc時間戳轉換成struct_time格式
23 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) # 將utc struct_time格式轉成指定的字符串格式
24 
25 
26 # 時間加減
27 print(datetime.datetime.now())           # 返回當前時間 2017-05-07 22:36:45.179732
28 print(datetime.date.fromtimestamp(time.time()))  # 時間戳直接轉換成日期格式 2017-05-07
29 print(datetime.datetime.now() + datetime.timedelta(3))    # 返回時間在當前日期上 +3 天
30 print(datetime.datetime.now() + datetime.timedelta(-3))    # 返回時間在當前日期上 -3 天
31 print(datetime.datetime.now() + datetime.timedelta(hours= 3)) # 返回時間在當前時間上 +3 小時
32 print(datetime.datetime.now() + datetime.timedelta(minutes= 30)) # 返回時間在當前時間上 +30 分鍾
33 
34 c_time  = datetime.datetime.now()
35 print(c_time)                          # 當前時間為 2017-05-07 22:52:44.016732
36 print(c_time.replace(minute=3,hour=2)) # 時間替換 替換時間為‘2017-05-07 02:03:18.181732’
37 
38 print(datetime.timedelta)      # 表示時間間隔,即兩個時間點之間的長度
39 print (datetime.datetime.now() - datetime.timedelta(days=5))  # 返回時間在當前時間上 -5 天
40 
41 # python 日歷模塊
42 import calendar
43 
44 print(calendar.calendar(theyear= 2017))     # 返回2017年整年日歷
45 print(calendar.month(2017,5))               # 返回某年某月的日歷,返回類型為字符串類型
46 
47 calendar.setfirstweekday(calendar.WEDNESDAY) # 設置日歷的第一天(第一天以星期三開始)
48 cal = calendar.month(2017, 4)
49 print (cal)
50 
51 print(calendar.monthrange(2017,5))        # 返回某個月的第一天和這個月的所有天數
52 print(calendar.monthcalendar(2017,5))     # 返回某個月以每一周為元素的序列
53 
54 cal = calendar.HTMLCalendar(calendar.MONDAY)
55 print(cal.formatmonth(2017, 5))           # 在html中打印某年某月的日歷
56 
57 print(calendar.isleap(2017))             # 判斷是否為閏年
58 print(calendar.leapdays(2000,2017))       # 判斷兩個年份間閏年的個數

 

二、random模塊

 1 import random
 2 
 3 # 隨機數
 4 print(random.random())              # 返回一個隨機小數'0.4800545746046827'
 5 print(random.randint(1,5))          # 返回(1-5)隨機整型數據
 6 print(random.randrange(1,10))       # 返回(1-10)隨機數據
 7 
 8 # 生成隨機驗證碼
 9 code = ''
10 for i in range(4):
11     current = random.randrange(0,4)
12     if current != i:
13         temp = chr(random.randint(65,90))
14     else:
15         temp = random.randint(0,9)
16     code += str(temp)
17 
18 print(code)


三、OS模塊

 1 import os
 2 
 3 print(os.getcwd())        # 獲得當前工作目錄
 4 print(os.chdir("dirname")) # 改變當前腳本的工作路徑,相當於shell下的cd
 5 print(os.curdir)            # 返回當前目錄‘.'
 6 print(os.pardir)            # 獲取當前目錄的父目錄字符串名‘..'
 7 print(os.makedirs('dirname1/dirname2'))     # 可生成多層遞歸目錄
 8 print(os.removedirs('dirname1/dirname2'))      # 若目錄為空,則刪除,並遞歸到上一級目錄,如若也為空,則刪除,依此類推
 9 print(os.mkdir('test4'))         # 生成單級目錄;相當於shell中mkdir dirname
10 print(os.rmdir('test4'))        # 刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname
11 print(os.listdir('/pythonStudy/s12/test'))   # 列出指定目錄下的所有文件和子目錄,包括隱藏文件,並以列表方式打印
12 print(os.remove('log.log'))            # 刪除一個指定的文件
13 print(os.rename("oldname","newname"))    # 重命名文件/目錄)
14 print(os.stat('/pythonStudy/s12/test'))     # 獲取文件/目錄信息
15 print(os.pathsep)            # 輸出用於分割文件路徑的字符串';'
16 print(os.name)               # 輸出字符串指示當前使用平台。win->'nt'; Linux->'posix'
17 print(os.system(command='bash'))   # 運行shell命令,直接顯示
18 print(os.environ)                  # 獲得系統的環境變量
19 print(os.path.abspath('/pythonStudy/s12/test'))   # 返回path規范化的絕對路徑
20 print(os.path.split('/pythonStudy/s12/test'))     # 將path分割成目錄和文件名二元組返回
21 print(os.path.dirname('/pythonStudy/s12/test'))    # 返回path的目錄。其實就是os.path.split(path)的第一個元素
22 print(os.path.basename('/pythonStudy/s12/test'))   # 返回path最后的文件名。如果path以/或\結尾,那么就會返回空值。即os.path.split(path)的第二個元素
23 print(os.path.exists('test'))                 # 判斷path是否存在
24 print(os.path.isabs('/pythonStudy/s12/test'))    # 如果path是絕對路徑,返回True
25 print(os.path.isfile('test'))                   # 如果path是一個存在的文件,返回True。否則返回False
26 print(os.path.isdir('/pythonStudy/s12/test'))    # 如果path是一個存在的目錄,則返回True。否則返回False
27 print(os.path.getatime('/pythonStudy/s12/test'))   # 返回path所指向的文件或者目錄的最后存取時間
28 print(os.path.getmtime('/pythonStudy/s12/test'))   # 返回path所指向的文件或者目錄的最后修改時間


四、sys模塊

1 import sys
2 
3 print(sys.argv)          # 命令行參數List,第一個元素是程序本身路徑
4 print(sys.exit(n))     # 退出程序,正常退出時exit(0)
5 print(sys.version)       # 獲取python的版本信息
6 print(sys.path)          # 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
7 print(sys.platform)      # 返回操作平台的名稱


五、shutil模塊

 1 import shutil
 2 shutil.copyfileobj(fsrc, fdst, length=16*1024)      # 將文件內容拷貝到另一個文件中,可以是部分內容
 3 shutil.copyfile(src, dst)                           # 拷貝文件
 4 shutil.copymode(src, dst)                           # 僅拷貝權限。內容、組、用戶均不變
 5 shutil.copystat(src, dst)                           # 拷貝狀態的信息,包括:mode bits, atime, mtime, flags
 6 shutil.copy(src, dst)                               # 拷貝文件和權限
 7 shutil.copy2(src, dst)                              # 拷貝文件和狀態信息
 8 shutil.move(src, dst)                               # 遞歸的去移動文件
 9 
10 # base_name: 壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑
11 # format: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
12 # root_dir: 要壓縮的文件夾路徑(默認當前目錄)
13 # owner: 用戶,默認當前用戶
14 # group: 組,默認當前組
15 # logger: 用於記錄日志,通常是logging.Logger對象
16 shutil.make_archive(base_name, format,root_dir,owner,group,logger)   # 創建壓縮包並返回文件路徑,例如:zip、tar
17 
18 shutil 對壓縮包的處理是調用 ZipFile 和 TarFile 兩個模塊來進行的:
19 
20 # zipfile 壓縮解壓
21 
22 import zipfile
23 # 壓縮
24 z = zipfile.ZipFile('laxi.zip', 'w')
25 z.write('a.log')
26 z.write('data.data')
27 z.close()
28 
29 # 解壓
30 z = zipfile.ZipFile('laxi.zip', 'r')
31 z.extractall()
32 z.close()
33 
34 # tarfile 壓縮解壓
35 
36 import tarfile
37 
38 # 壓縮
39 tar = tarfile.open('your.tar','w')
40 tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
41 tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
42 tar.close()
43 
44 # 解壓
45 tar = tarfile.open('your.tar','r')
46 tar.extractall()  # 可設置解壓地址
47 tar.close()


六、XML處理模塊

 

  1 # xml的格式如下,就是通過<>節點來區別數據結構的:
  2 xmltest.xml
  3 
  4 <?xml version="1.0"?>
  5 
  6 <data>
  7 
  8     <country name="Liechtenstein">
  9 
 10         <rank updated="yes">2</rank>
 11 
 12         <year>2008</year>
 13 
 14         <gdppc>141100</gdppc>
 15 
 16         <neighbor name="Austria" direction="E"/>
 17 
 18         <neighbor name="Switzerland" direction="W"/>
 19 
 20     </country>
 21 
 22     <country name="Singapore">
 23 
 24         <rank updated="yes">5</rank>
 25 
 26         <year>2011</year>
 27 
 28         <gdppc>59900</gdppc>
 29 
 30         <neighbor name="Malaysia" direction="N"/>
 31 
 32     </country>
 33 
 34     <country name="Panama">
 35 
 36         <rank updated="yes">69</rank>
 37 
 38         <year>2011</year>
 39 
 40         <gdppc>13600</gdppc>
 41 
 42         <neighbor name="Costa Rica" direction="W"/>
 43 
 44         <neighbor name="Colombia" direction="E"/>
 45 
 46     </country>
 47 
 48 </data> 
 49 
 50 
 51 #  xml協議在各個語言里的都 是支持的,在python中可以用以下模塊操作xml  
 52 
 53 import xml.etree.ElementTree as ET
 54 
 55 tree = ET.parse("xmltest.xml")
 56 root = tree.getroot()
 57 print(root.tag)
 58 
 59 #遍歷xml文檔
 60 for child in root:
 61     print(child.tag, child.attrib)
 62     for i in child:
 63         print(i.tag,i.text)
 64 
 65 #只遍歷year 節點
 66 for node in root.iter('year'):
 67     print(node.tag,node.text)
 68 
 69 
 70 # 修改和刪除xml文檔內容
 71 
 72 import xml.etree.ElementTree as ET
 73 
 74 tree = ET.parse("xmltest.xml")
 75 root = tree.getroot()
 76 
 77 #修改
 78 
 79 for node in root.iter('year'):
 80     new_year = int(node.text) + 1
 81     node.text = str(new_year)
 82     node.set("updated","yes")
 83 tree.write("xmltest.xml")
 84 
 85 #刪除node
 86 
 87 for country in root.findall('country'):
 88    rank = int(country.find('rank').text)
 89    if rank > 50:
 90        root.remove(country)
 91 tree.write('output.xml')
 92 
 93 
 94 # 自己創建xml文檔
 95 import xml.etree.ElementTree as ET
 96 
 97 new_xml = ET.Element("namelist")
 98 name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
 99 age = ET.SubElement(name, "age", attrib={"checked": "no"})
100 age = ET.SubElement(name, "age")
101 age.text = '33'
102 name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
103 age = ET.SubElement(name2, "age")
104 age.text = '19'
105 et = ET.ElementTree(new_xml)  # 生成文檔對象
106 et.write("test.xml", encoding="utf-8", xml_declaration=True)
107 ET.dump(new_xml)  # 打印生成的格式


七、configparser模塊

     用於生成和修改常見配置文檔

 

 1 # 好多軟件的常見文檔格式如下
 2  [DEFAULT]
 3  compressionlevel = 9
 4  serveraliveinterval = 45
 5  compression = yes
 6  forwardx11 = yes
 7  
 8  [bitbucket.org]
 9  user = hg
10  
11  [topsecret.server.com]
12  host port = 50022
13  forwardx11 = no
14  
15  # python 生成一個這樣的文檔
16  
17  import configparser
18  
19  config = configparser.ConfigParser()
20  
21  config["DEFAULT"] = {'ServerAliveInterval': '45',
22                       'Compression': 'yes',
23                       'CompressionLevel': '9'}
24  
25  config['bitbucket.org'] = {}
26  config['bitbucket.org']['User'] = 'hg'
27  config['topsecret.server.com'] = {}
28  topsecret = config['topsecret.server.com']
29  topsecret['Host Port'] = '50022'
30  topsecret['ForwardX11'] = 'no'
31  config['DEFAULT']['ForwardX11'] = 'yes'
32  with open('example.ini', 'w') as configfile:
33      config.write(configfile)
34  
35  
36  
37  # 寫完了還可以再讀出來
38  
39  import configparser
40  config = configparser.ConfigParser()
41  config.sections()
42  file = config.read('example.ini')
43  print(file)      # ['example.ini']
44  
45  title = config.sections()
46  print(title)     # ['bitbucket.org', 'topsecret.server.com']
47  
48  print('bitbucket.org' in config)     # True
49  print('bytebong.com' in config)      # False
50  print(config['bitbucket.org']['User'])   # hg
51  print(config['DEFAULT']['Compression'])   # yes
52  
53  topsecret = config['topsecret.server.com']
54  print(topsecret['ForwardX11'])           # no
55  print(topsecret['Host Port'])         # 50022
56  
57  for key in config['topsecret.server.com']:
58      print(key)
59  '''
60    輸出結果:
61              host port
62              forwardx11
63              compressionlevel
64              serveraliveinterval
65              compression
66  '''
67  print(config['topsecret.server.com']['Compression'])   # yes
68 
69 # configparser增刪改查語法
70 import configparser
71 
72 config = configparser.ConfigParser()
73 config.read('i.cfg')
74 
75 secs = config.sections()       # 返回配置文件中的主節點
76 print (secs)
77 
78 options = config.options('bitbucket.org')
79 print(options)                 # 返回所有子節點信息
80 
81 item_list = config.items('bitbucket.org')
82 print(item_list)              # 列出所有子節點詳細信息
83 
84 val = config.get('topsecret.server.com','host port')
85 print(val)                    # 返回單個子節點信息
86 
87 val2 = config.getint('topsecret.server.com','host port')
88 print(val2)
89 
90 # 刪除'bitbucket.org'
91 sec = config.remove_section('bitbucket.org')
92 config.write(open('i.cfg','w'))
93 
94 
95 sec2 = config.add_section('huhuan2')      # 添加主節點
96 config.set('huhuan2','k','1111')          # 添加子節點
97 config.set('huhuan','kk','2222')
98 config.remove_option('huhuan','kk')       # 刪除子節點
99 config.write(open('i.cfg','w'))

 

八、hashlib模塊

  用於加密相關的操作

 1 import hashlib
 2 
 3 # ****** md5 ******
 4 m =hashlib.md5()
 5 m.update(b'hello')
 6 print(m.hexdigest())     # 16進制格式
 7 print(m.digest())        # 2進制格式
 8 
 9 # ****** shal ******
10 hash = hashlib.sha1()
11 hash.update(b'hello')
12 print(hash.hexdigest())
13 
14 # ****** sha224 ******
15 hash = hashlib.sha224()
16 hash.update(b'hello')
17 print(hash.hexdigest())
18 
19 # ****** sha256 ******
20 hash = hashlib.sha256()
21 hash.update(b'hello')
22 print(hash.hexdigest())
23 
24 # ****** sha384 ******
25 hash = hashlib.sha384()
26 hash.update(b'hello')
27 print(hash.hexdigest())
28 
29 # ****** sha512 ******
30 hash = hashlib.sha512()
31 hash.update(b'hello')
32 print(hash.hexdigest())
33 
34 運行結果:
35 5d41402abc4b2a76b9719d911017c592
36 b']A@*\xbcK*v\xb9q\x9d\x91\x10\x17\xc5\x92'
37 aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
38 ea09ae9cc6768c50fcee903ed054556e5bfc8347907f12598aa24193
39 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
40 59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553bcdb9c666fa90125a3c79f90397bdf5f6a13de828684f
41 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043


九、logging 模塊

  python的logging模塊提供了標准的日志接口,你可以通過它存儲各種格式的日志,logging的日志可以分為 debug()info()warning()error() and critical() 5個級別。

 1 import logging
 2 
 3 # %(message)s 日志信息
 4 # %(levelno)s 日志級別
 5 # datefmt  設置時間格式
 6 # filename  設置日志保存的路徑
 7 # level=loggin.INFO意思是,把日志紀錄級別設置為INFO,也就是說,只有比日志是INFO或比INFO級別更高的日志才會被紀錄到文件里,
 8 # 在這個例子, 第一條日志是不會被紀錄的,如果希望紀錄debug的日志,那把日志級別改成DEBUG就行了。
 9 logging.basicConfig(format='%(asctime)s %(message)s %(levelno)s', datefmt='%m/%d/%Y %I:%M:%S %p',filename='example.log',level=logging.INFO)
10 logging.debug('This message should go to the log file')
11 logging.info('So should this')

日志格式

%(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

用戶輸出的消息

 1 # 對於等級:
 2 
 3 CRITICAL = 50
 4 
 5 ERROR = 40
 6 
 7 WARNING = 30
 8 
 9 INFO = 20
10 
11 DEBUG = 10
12 
13 NOTSET = 0

Python 使用logging模塊記錄日志涉及四個主要類:

logger提供了應用程序可以直接使用的接口;

handler將(logger創建的)日志記錄發送到合適的目的輸出;

filter提供了細度設備來決定輸出哪條日志記錄;

formatter決定日志記錄的最終輸出格式。

logger :

每個程序在輸出信息之前都要獲得一個Logger。Logger通常對應了程序的模塊名,比如聊天工具的圖形界面模塊可以這樣獲得它的Logger: LOG=logging.getLogger(”chat.gui”)

而核心模塊可以這樣: LOG=logging.getLogger(”chat.kernel”)

Logger.setLevel(lel):指定最低的日志級別,低於lel的級別將被忽略。debug是最低的內置級別,critical為最高

Logger.addFilter(filt)、Logger.removeFilter(filt):添加或刪除指定的filter

Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或刪除指定的handler

Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以設置的日志級別

handler

handler

對象負責發送相關的信息到指定目的地。Python的日志系統有多種Handler可以使用。有些Handler可以把信息輸出到控制台,有些Logger可以把信息輸出到文件,還有些 Handler可以把信息發送到網絡上。如果覺得不夠用,還可以編寫自己的Handler。可以通過

addHandler()方法添加多個多handler

Handler.setLevel(lel):指定被處理的信息級別,低於lel級別的信息將被忽略

Handler.setFormatter():給這個handler選擇一個格式

Handler.addFilter(filt)、Handler.removeFilter(filt):新增或刪除一個filter對象

每個Logger可以附加多個Handler。接下來我們就來介紹一些常用的Handler:
1)    logging.StreamHandler
使用這個Handler可以向類似與sys.stdout或者sys.stderr的任何文件對象(file object)輸出信息。它的構造函數是:
StreamHandler([strm])
其中strm參數是一個文件對象。默認是sys.stderr

2)   logging.FileHandler
和StreamHandler類似,用於向一個文件輸出日志信息。不過FileHandler會幫你打開這個文件。它的構造函數是:
FileHandler(filename[,mode])
filename是文件名,必須指定一個文件名。
mode是文件的打開方式。參見Python內置函數open()的用法。默認是’a',即添加到文件末尾。

3)   logging.handlers.RotatingFileHandler
這個Handler類似於上面的FileHandler,但是它可以管理文件大小。當文件達到一定大小之后,它會自動將當前日志文件改名,然后創建 一個新的同名日志文件繼續輸出。比如日志文件是chat.log。當chat.log達到指定的大小之后,RotatingFileHandler自動把 文件改名為chat.log.1。不過,如果chat.log.1已經存在,會先把chat.log.1重命名為chat.log.2。。。最后重新創建 chat.log,繼續輸出日志信息。它的構造函數是:
RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
其中filename和mode兩個參數和FileHandler一樣。
maxBytes用於指定日志文件的最大文件大小。如果maxBytes為0,意味着日志文件可以無限大,這時上面描述的重命名過程就不會發生。
backupCount用於指定保留的備份文件的個數。比如,如果指定為2,當上面描述的重命名過程發生時,原有的chat.log.2並不會被更名,而是被刪除。

4)   logging.handlers.TimedRotatingFileHandler
這個Handler和RotatingFileHandler類似,不過,它沒有通過判斷文件大小來決定何時重新創建日志文件,而是間隔一定時間就 自動創建新的日志文件。重命名的過程與RotatingFileHandler類似,不過新的文件不是附加數字,而是當前時間。它的構造函數是:
TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
其中filename參數和backupCount參數和RotatingFileHandler具有相同的意義。
interval是時間間隔。
when參數是一個字符串。表示時間間隔的單位,不區分大小寫。它有以下取值:
S 秒
M 分
H 小時
D 天
W 每星期(interval==0時代表星期一)
midnight 每天凌晨

 1 import logging
 2 
 3 logger = logging.getLogger('TEST_LOG')    # 獲得一個Logger
 4 logger.setLevel(logging.DEBUG)            # 設置日志級別
 5 
 6 ch = logging.StreamHandler()            # logging.StreamHandler這個Handler可以向類似與sys.stdout或者sys.stderr的任何文件對象(file object)輸出信息。
 7 ch.setLevel(logging.DEBUG)
 8 
 9 fh = logging.FileHandler("access.log")  # 用於向一個文件輸出日志信息。不過FileHandler會幫你打開這個文件
10 fh.setLevel(logging.WARNING)
11 
12 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')  # 設置日志記錄的最終輸出格式
13 
14 ch.setFormatter(formatter)
15 fh.setFormatter(formatter)
16 
17 # 添加ch,fh到logger
18 logger.addHandler(ch)
19 logger.addHandler(fh)
20 
21 
22 logger.debug('debug message')
23 logger.info('info message')
24 logger.warn('warn message')
25 logger.error('error message')
26 logger.critical('critical message')

文件自動截斷實例:

 1 import logging
 2 from logging import handlers
 3 
 4 logger = logging.getLogger(__name__)
 5 log_file = "timelog.log"
 6 fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3)
 7 #fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3)
 8 
 9 formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s')
10 fh.setFormatter(formatter)
11 
12 logger.addHandler(fh)
13 
14 logger.warning("test1")
15 logger.warning("test12")
16 logger.warning("test13")
17 logger.warning("test14")

十、subprocess模塊(待定)

十一、json & pickle 模塊

用於序列化的兩個模塊

  • json,用於字符串 和 python數據類型間進行轉換
  • pickle,用於python特有的類型 和 python的數據類型間進行轉換

Json模塊提供了四個功能:dumps、dump、loads、load

pickle模塊提供了四個功能:dumps、dump、loads、load

 1 import pickle
 2 
 3 date = {'k1':'123','k2':'hello'}
 4 
 5 str = pickle.dumps(date)    # pickle.dumps 將數據通過特殊的形式轉換為只有python認識的字符串
 6 print(str)
 7 
 8 with open('result.pk','w') as fp:  # pickle.dump 將數據通過特殊的形式轉換為只有python認識的字符串並寫入文件
 9     pickle.dump(date,fp)
10 
11 import json
12 
13 str1 = json.dumps(date)     # json.dumps 將數據通過特殊形式轉換為所有程序語言都認識的字符串
14 print(str1)
15 
16 with open('result1.json','w') as fp:  #json.dump 將數據通過特殊的形式轉換為只有python認識的字符串並寫入文件
17     json.dump(date,fp)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM