首页 > 解决方案 > Python 中的异常处理 - mysql.connector

问题描述

我有 2 个 pyton 程序 1) 'Prog1.py' 处理数据库 - 从数据库中查询 2) 'Prog2.py' 包含如下主运行循环

#importing the database class from Prog1.py (mysql.connector used to in Prog1.py)
from database import Database
...

#main run loop
while(True):
   time.sleep(0.2)
   for loc in data:
         self.datafunc(loc)
         call_func_fromprg1()
         foo()
         bar()
    #not to run these conditions if exception is met
    if expression1:
        then operation1
    if expression1:
        then operation2
    if expression3:
        then operation3
    if expression4:
        then operation4

    var = time()

我正在尝试在call_func_fromprg1()调用 Prog1.py 的函数并引发错误的地方 创建一个错误异常,mysql.connector.errors.InternalError : Deadlock found when try to get lock 并跳过 while 循环的其余部分,最后不更新时间并在 0.2 秒后再次重新循环,如代码中所示。

我需要的是编写以下条款的最佳位置

try:
...
except:
 continue
...

标签: pythonmysqlexception-handlingmysql-python

解决方案


一种方法是在 prog2.py 中创建一个状态变量,如下所示。

from database import Database
...

#main run loop
while(True):
   time.sleep(0.2)
   for loc in data:
         self.datafunc(loc)
         status = call_func_fromprg1()
         foo()
         bar()
    #not to run these conditions if exception is met
    if expression1:
        then operation1
    if expression1:
        then operation2
    if expression3:
        then operation3
    if expression4:
        then operation4
    if status:
        var = time()

并在 prog1.py 中创建一个返回 True 值,如下所示:

def function():
    try:
        # your code here
        #
        return True
    except:
        #Exception codes
        return False

推荐阅读