How to turn off warning message prompt by Python
This article introduces the knowledge of "how to turn off warning information prompts by Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Background
When executing a sql command using python MySQLdb, if the result contains warning, it will be written to the stderr and displayed to the terminal command line. In fact, these warning prompts do not have any practical effect.
Root@rac3:~/scripts# > python set_ms.py-m 10.0.2.15 virtual 3306-s 10.0.2.6purl 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
So what are we gonna do about it?
Python provides the warnings module, which controls the output form of the system warning and turns it off or on. For instance
1 pass MySQLdb.Warning warnings into exceptions so that exception can be obtained through try catch and then processed by business logic.
Filterwarnings ('error', category=MySQLdb.Warning)
If set to error, you need to introduce the except mechanism into the code
Try:
ExecSQL...
Except MySQLdb.Warning, e:
Print "MySQLdb Warning", e
2 set warning to ignore and ignore all warning information.
Filterwarnings ('ignore', category = MySQLdb.Warning)
Code implementation
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% dvv% s"% (e.args [0], e.args [1])
Sys.exit (9)
This is the end of the content of "how to turn off warning Information Tips by Python". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!