python:常用模組二,python模組
1,hashlib模組---摘要演算法
import hashlib md5 = hashlib.md5()md5.update('how to use md5 in python hashlib?')print md5.hexdigest()計算結果如下:d26a53750bc40b38b65a520292f69306用MD5進行加密
如果資料量很大,可以分塊多次調用update(),最後計算的結果是一樣的:
md5 = hashlib.md5()md5.update('how to use md5 in ')md5.update('python hashlib?')print md5.hexdigest()
MD5是最常見的摘要演算法,速度很快,產生結果是固定的128 bit位元組,通常用一個32位的16進位字串表示。另一種常見的摘要演算法是SHA1,調用SHA1和調用MD5完全類似:
import hashlib sha1 = hashlib.sha1()sha1.update('how to use sha1 in ')sha1.update('python hashlib?')print sha1.hexdigest()
SHA1的結果是160 bit位元組,通常用一個40位的16進位字串表示。比SHA1更安全的演算法是SHA256和SHA512,不過越安全的演算法越慢,而且摘要長度更長。
2,configparser模組
該模組適用於設定檔的格式與windows ini檔案類似,可以包含一個或多個節(section),每個節可以有多個參數(鍵=值)。
建立檔案
來看一個好多軟體的常見文檔格式如下:
[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes [bitbucket.org]User = hg [topsecret.server.com]Port = 50022ForwardX11 = no
如果想用python產生一個這樣的文檔怎麼做呢?
import configparserconfig =configparser.ConfigParser()config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11':'yes' }config['bitbucket.org'] = {'User':'hg'}config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}with open('example.ini', 'w') as configfile: config.write(configfile)尋找檔案
import configparserconfig = configparser.ConfigParser()#---------------------------尋找檔案內容,基於字典的形式print(config.sections()) # []config.read('example.ini')print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']print('bytebong.com' in config) # Falseprint('bitbucket.org' in config) # Trueprint(config['bitbucket.org']["user"]) # hgprint(config['DEFAULT']['Compression']) #yesprint(config['topsecret.server.com']['ForwardX11']) #noprint(config['bitbucket.org']) #<Section: bitbucket.org>for key in config['bitbucket.org']: # 注意,有default會預設default的鍵 print(key)print(config.options('bitbucket.org')) # 同for迴圈,找到'bitbucket.org'下所有鍵print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有索引值對print(config.get('bitbucket.org','compression')) # yes get方法Section下的key對應的value增刪改操作
import configparserconfig = configparser.ConfigParser()config.read('example.ini')config.add_section('yuan')config.remove_section('bitbucket.org')config.remove_option('topsecret.server.com',"forwardx11")config.set('topsecret.server.com','k1','11111')config.set('yuan','k2','22222')config.write(open('new2.ini', "w"))logging模組函數式簡單配置
import logging logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
預設情況下Python的logging模組將日誌列印到了標準輸出中,且只顯示了大於等於WARNING層級的日誌,這說明預設的記錄層級設定為WARNING(記錄層級等級CRITICAL > ERROR > WARNING > INFO > DEBUG),預設的日誌格式為記錄層級:Logger名稱:使用者輸出訊息。
靈活配置記錄層級,日誌格式,輸出位置:
import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='/tmp/test.log', filemode='w') logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
配置參數:
logging.basicConfig()函數中可通過具體參數來更改logging模組預設行為,可用參數有:filename:用指定的檔案名稱建立FiledHandler,這樣日誌會被儲存在指定的檔案中。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使用者輸出的訊息
View Codelogger對象配置
import logginglogger = logging.getLogger()# 建立一個handler,用於寫入記錄檔fh = logging.FileHandler('test.log',encoding='utf-8') # 再建立一個handler,用於輸出到控制台 ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')fh.setLevel(logging.DEBUG)fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(fh) #logger對象可以添加多個fh和ch對象 logger.addHandler(ch) logger.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message')