溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python怎么關(guān)閉warning信息提示

發(fā)布時(shí)間:2021-09-15 17:59:06 來(lái)源:億速云 閱讀:205 作者:chen 欄目:MySQL數(shù)據(jù)庫(kù)

本篇內(nèi)容介紹了“Python怎么關(guān)閉warning信息提示”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

背景
在使用 python MySQLdb 執(zhí)行sql 命令的時(shí)候,如果執(zhí)行結(jié)果含有warning,則會(huì)被寫(xiě)入到 stderr 展示到終端命令行。其實(shí)這些warning提示信息沒(méi)有任何實(shí)際的作用。
root@rac3:~/scripts# >python set_ms.py -m 10.0.2.15:3306 -s 10.0.2.6:3308 
Begin to set Replicate on slave 10.0.2.6:3308
set_ms.py:35: Warning: Slave already has been stopped
  ret=cursor.execute(SQL)
set_ms.py:35: Warning: Sending passwords in plain text without SSL/TLS is extremely insecure.
  ret=cursor.execute(SQL)
set_ms.py:35: Warning: Storing MySQL user name or password information in the master info repository is not secure and is therefore not recommended. Please consider using the USER and PASSWORD connection options for START SLAVE; see the 'START SLAVE Syntax' in the MySQL Manual for more information.
  ret=cursor.execute(SQL)
Success : CHANGE MASTER TO MASTER_HOST='10.0.2.15',MASTER_USER='slave',MASTER_PASSWORD='xxxx',MASTER_PORT=3306,MASTER_LOG_FILE='mysql-bin.000002', MASTER_LOG_POS=314;
那我們?cè)撛趺唇鉀Q呢?
Python 提供了warnings模塊,通過(guò)該模塊控制系統(tǒng)warning 的輸出形式,關(guān)閉或者打開(kāi)。舉個(gè)例子 
1 將  MySQLdb.Warning warnings 傳入exceptions 以便通過(guò) try  catch 獲取exception 進(jìn)而對(duì)其進(jìn)行業(yè)務(wù)邏輯處理。
   filterwarnings('error', category=MySQLdb.Warning) 
 如果設(shè)置為error 則需要在代碼中引入 except機(jī)制
  try:
        execSQL ...
   except MySQLdb.Warning, e:
        print "MySQLdb Warning", e

 2 設(shè)置為warning 為 ignore ,忽略所有warning 信息。
  filterwarnings('ignore', category = MySQLdb.Warning)

代碼實(shí)現(xiàn)
import MySQLdb
import MySQLdb.cursors
from warnings import filterwarnings
filterwarnings('ignore', category = MySQLdb.Warning)
def execSql(SQL,IP,PORT,USER,PWD):
  '''####exec_sql####'''
  try:
      db=MySQLdb.connect(host=IP,user=USER,passwd=PWD,db='test',port=int(PORT),charset="utf8")
      cursor=db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
  except MySQLdb.Error,e:
      print "connection failed!Error %d:%s"%(e.args[0],e.args[1])
      sys.exit(9)

Python怎么關(guān)閉warning信息提示

“Python怎么關(guān)閉warning信息提示”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI