【Python】關閉 warning 資訊提示

楊奇龍發表於2016-02-03
背景
在使用 python MySQLdb 執行sql 命令的時候,如果執行結果含有warning,則會被寫入到 stderr 展示到終端命令列。其實這些warning提示資訊沒有任何實際的作用。
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;
那我們該怎麼解決呢?
Python 提供了warnings模組,通過該模組控制系統warning 的輸出形式,關閉或者開啟。舉個例子 
1 將  MySQLdb.Warning warnings 傳入exceptions 以便通過 try  catch 獲取exception 進而對其進行業務邏輯處理。
   filterwarnings('error', category=MySQLdb.Warning) 
 如果設定為error 則需要在程式碼中引入 except機制
  try:
        execSQL ...
   except MySQLdb.Warning, e:
        print "MySQLdb Warning", e

2 設定為warning 為 ignore ,忽略所有warning 資訊。
  filterwarnings('ignore', category = MySQLdb.Warning)

程式碼實現
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 官方的 Warning control  介紹的非常詳細,想深入瞭解python 對warning 管理的同學可以認真閱讀。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22664653/viewspace-1986069/,如需轉載,請註明出處,否則將追究法律責任。

相關文章