python捕捉warning_Python 怎么捕获 MySQLdb.Warning ?

Python 初学者,我在写一个基础类,有个导入文件进 MySQL 的方法,导入时不免会有一些 warning ,我想把 warning 捕获。然后返回给上层业务代码。

xxx.py:247: Warning: Data truncated for column 'cost' at row 2004

cursor.execute(load_data_sql)

xxx.py:247: Warning: Row 2004 was truncated; it contained more data than there were input columns

cursor.execute(load_data_sql)

xxx.py:247: Warning: Data truncated for column 'cost' at row 3519

cursor.execute(load_data_sql)

xxx.py:247: Warning: Row 3519 was truncated; it contained more data than there were input columns

cursor.execute(load_data_sql)

xxx.py:247: Warning: Data truncated for column 'cost' at row 5280

cursor.execute(load_data_sql)

xxx.py:247: Warning: Row 5280 was truncated; it contained more data than there were input columns

cursor.execute(load_data_sql)

xxx.py:247: Warning: Data truncated for column 'cost' at row 7034

cursor.execute(load_data_sql)

xxx.py:247: Warning: Row 7034 was truncated; it contained more data than there were input columns

cursor.execute(load_data_sql)

xxx.py:247: Warning: Data truncated for column 'cost' at row 8801

cursor.execute(load_data_sql)

xxx.py:247: Warning: Row 8801 was truncated; it contained more data than there were input columns

cursor.execute(load_data_sql)

……

我尝试了一下:

cursor = db.cursor()

load_data_sql = "LOAD DATA INFILE \'%s\' IGNORE INTO TABLE %s" \

% (cleaned_file_path, table)

# 捕获 warn

warnings.filterwarnings('error')

warn = ''

try:

cursor.execute(load_data_sql)

db.commit()

except MySQLdb.Error as e:

db.rollback()

return {

'status': -1,

'message': "load data file sql \"%s\" error: %s" % (load_data_sql, e)

}

except MySQLdb.Warning as e:

return {

'status': -2,

'message': "load data file sql \"%s\" warning: %s" % (load_data_sql, e)

}

else:

return {

'status': 0,

'message': 'success'

}

finally:

db.close()

上层业务会打日志:

warning: Data truncated for column 'cost' at row 2004

貌似还行,除了忽略的行,其它数据都导入成功了。但总感觉代码有点 hack ( filterwarnings ),而且只能捕获到一条 Warning ,应该会有很多条的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值