1. 程式人生 > >Python 模塊學習2

Python 模塊學習2

sage 發生 HR ear list 管理 func tro 變量

(1)configparse模塊 如何創建如下配置文件 [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no import configparser conf = configparser.ConfigParser() #直接創建 conf[‘DEFAULT‘] = {‘ServerAliveInterval‘: ‘45‘, ‘Compression‘: ‘yes‘, ‘CompressionLevel‘: ‘9‘, ‘ForwardX11‘: ‘yes‘ } conf[‘bitbucket.org‘] = {} conf[‘bitbucket.org‘][‘User‘] = ‘hg‘ conf[‘topsecret.server.com‘] = {} topsecret = conf[‘topsecret.server.com‘] topsecret[‘Host Port‘] = ‘50022‘ topsecret[‘ForwardX11‘] = ‘no‘ conf[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘ with open(‘conf.ini‘, ‘w‘) as conf_file: conf.write(conf_file) #--------------------讀 conf.read(‘conf.ini‘, encoding=‘utf8‘) f = conf.sections() print(f) [‘bitbucket.org‘, ‘topsecret.server.com‘] d = conf.options(‘bitbucket.org‘) print(d) print(conf.default_section) #?發現沒有打印?如何去讀出DEFAULT呢 DEFAULT print(list(conf[‘topsecret.server.com‘].values()))#取值和字典類似 [‘50022‘, ‘no‘, ‘45‘, ‘yes‘, ‘9‘] #當自定義section和默認section時有相同的值時,這是取出的是自定義的那部分的值 if ‘ServerAliveInterval‘ in conf[‘DEFAULT‘]: #也可以判斷摸個值是否存在 print(‘yes‘) else: print(‘no‘) #############增 conf.add_section(‘groups‘) conf[‘groups‘] = { ‘name‘: ‘alex‘, ‘age‘: ‘18‘ } with open(‘conf.ini‘, ‘r+‘, encoding=‘utf8‘) as file: conf.write(file) ##########改 conf.set(‘groups‘, ‘age‘, ‘34‘) conf.write(open(‘conf.ini‘, ‘r+‘)) ###########刪除內容 option是刪除某個系列下的某個值,section是刪除文件下某一部分 conf.read(‘conf.ini‘) conf.remove_option(‘groups‘, ‘name‘) conf.write(open(‘conf.ini‘, ‘r+‘)) conf.remove_section(‘groups‘) conf.write(open(‘conf.ini‘, ‘r+‘)) (2)hashlib模塊 import hashlib m = hashlib.md5() m.update(b‘hello‘) print(m.digest) hash = hashlib.sha256() hash.update(‘admin‘) print(hash.hexdigest()) (3)subprocess模塊 可以與操作系統交互 三種執行命令的方法 subprocess.run() #官方推薦 subprocess.call() subprocess.Popen() #上面各種方法的底層封裝 標準寫法 >>> subprocess.run([‘df‘,‘-h‘],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True) 涉及到管道|的命令的寫法 >>> subprocess.run(‘df -h|grep disk1‘,shell=True)#將接將該條命令交給系統去處理 >>> a=subprocess.call([‘ls‘,‘-l‘]) (4)logging模塊(參考) FATAL - 導致程序退出的嚴重系統級錯誤,不可恢復,當錯誤發生時,系統管理員需要立即介入,謹慎使用。 ERROR - 運行時異常以及預期之外的錯誤,也需要立即處理,但緊急程度低於FATAL,當錯誤發生時,影響了程序的正確執行。需要註意的是這兩種級別屬於服務自己的錯誤,需要管理員介入,用戶輸入出錯不屬於此分類。
WARN - 預期之外的運行時狀況,表示系統可能出現問題。對於那些目前還不是錯誤,然而不及時處理也會變成錯誤的情況,也可以記為WARN,如磁盤過低。 INFO - 有意義的事件信息,記錄程序正常的運行狀態,比如收到請求,成功執行。通過查看INFO,可以快速定位WARN,ERROR, FATAL。INFO不宜過多,通常情況下不超過TRACE的10%。 DEBUG - 與程序運行時的流程相關的詳細信息以及當前變量狀態。 TRACE - 更詳細的跟蹤信息。DEBUG和TRACE這兩種規範由項目組自己定義,通過該種日誌,可以查看某一個操作每一步的執行過程,可以準確定位是何種操作,何種參數,何種順序導致了某種錯誤的發生 主要分為四個部分:
  • Loggers:提供應用程序直接使用的接口
  • Handlers:將Loggers產生的日誌傳到指定位置
  • Filters:對輸出日誌進行過濾
  • Formatters:控制輸出格式

日誌級別

Level Numeric value When it’s used
DEBUG 10 Detailed information, typically of interest only when diagnosing problems.
INFO 20 Confirmation that things are working as expected.
WARNING 30 An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR 40 Due to a more serious problem, the software has not been able to perform some function.
CRITICAL 50 A serious error, indicating that the program itself may be unable to continue running.

#打印在控制臺上 import logging logging.warning(‘use error‘) logging.critical(‘sever is down‘) logging.info(‘111‘) logging.debug(‘222‘) logging.error(‘333‘) #記錄在文件中 logging.basicConfig(filename=‘logging_test.log‘, level=logging.INFO, format=‘%(asctime)s :%(levelname)s:%(message)s‘, datefmt=‘%Y-%m-%d‘ ‘%I:%M:%S‘ ‘%p‘ )#文件配置 logging.warning(‘lower power action‘) logging.info(‘use error‘) logging.debug(‘sever is down‘) #即可以記錄在文件中也可以在控制臺中 # 1.生成logger對象 # 2.生成handler對象 # 2.1把handler對象,綁定到logger # 3.生成formatter對象 # 3.1生成的formatter對象綁定handler對象 logger = logging.getLogger(‘MySQL‘) logger.setLevel(logging.DEBUG)#設置級別 s = logging.StreamHandler()#屏幕handler對象 s.setLevel(logging.INFO) #設置屏幕輸出級別 f = logging.FileHandler(‘web.log‘) #文件handler對象 f.setLevel(logging.DEBUG)#s設置文件級別 logger.addHandler(s) logger.addHandler(f) s.setFormatter(‘%(asctime)s :%(levelname)s:%(message)s‘) f.setFormatter(‘%(asctime)s :%(name)s:%(message)s‘)

Python 模塊學習2