如何向 python 函数添加异常?

How to add exception to python function?

美好的一天。我在 python 上编写了一个应用程序,它从 Avaya PBX 收集呼叫日志并将它们写入 mysql 数据库。它运行良好,但有时 PBX 出于某种原因发送一个空字符串并且程序失败。我在下面附上屏幕和代码。我知道您需要将函数包装在异常中:try except,但我不明白该怎么做。请告诉我该怎么做。enter image description here


def write_db(item, *agrs):
    connection = pymysql.connect(host='localhost',
                                 user='acdr',
                                 password='it8ejokd',
                                 db='avaya_cdr',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    DBTBL = "cdr102019"
    DBFLD = "Date_call, Time_call, `Sec_dur`, `clg_num_in_tag`, `dialed_num`, dep_called, dep_dialed"

    dep_num_call = find_dep(item[3].replace(' ', ''))
    name_dep_call = name_dep(dep_num_call)
    dep_num_dial = find_dep(item[4].replace(' ', ''))
    name_dep_dial = name_dep(dep_num_dial)

    item.append(name_dep_call)
    item.append(name_dep_dial)
    item[1] = item[1] + "00"

    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
            cursor.execute(sql, (item))
        connection.commit()
    finally:
        connection.close()

# Задаем адрес сервера
SERVER_ADDRESS = ('', 5100)

# Настраиваем сокет
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(SERVER_ADDRESS)
server_socket.listen(5)
print('server is running, please, press ctrl+c to stop')

# Слушаем запросы и пишем в db
while True:
    connection, address = server_socket.accept()

    data = connection.recv(1024)
    if not(b'\x00\x00\x00' in data) and not(b'1370' in data):
        str = data.decode("utf-8")
        item=[str[0:6],str[7:11],str[12:17],str[18:33],str[34:57]]
        print(item)
        write_db(item)

    connection.close()

您必须捕获异常,因此我们可以满足一些类型的需求,但为了确保让您起床 运行,您可以执行以下操作:)

try:
    with connection.cursor() as cursor:
        sql = (
                "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES " 
                "(%s,%s,%s,%s,%s,%s,%s)"
        )
        cursor.execute(
            sql,
            (item),
        )

    connection.commit()

except Exception as e:
    print("Error occurred: %s"% e)

finally:
    connection.close()

这应该可以解决问题。我在这里使用了 try/except/else/finally 的所有四个元素,并简要说明了它们何时执行。

try:
    with connection.cursor() as cursor:
        sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
        cursor.execute(sql, (item))
except Exception: # If this code fails, ignore it
    pass
else: # If the code inside 'try' succeeds, execute this code. 
    connection.commit()
finally: # Regardless of whether or not the code inside 'try' succeeds, execute this code
    connection.close()