Python 模組學習2

來源:互聯網
上載者:User

標籤:rest   運行時異常   func   ash   輸出   debug   詳細資料   系統   evel   

(1)configparse模組如何建立如下設定檔[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes [bitbucket.org]User = hg [topsecret.server.com]Port = 50022ForwardX11 = no  import configparserconf = 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 hashlibm = 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 logginglogging.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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.