python rrdtool try-catch语句


我有一个Python脚本,它用从数据库中提取的数据更新RRD文件。以下是Python代码的一小段

选择 | 换行 | 行号
  1. for i in range(numrowed):
  2.                 row = curred.fetchone()
  3.                 time_stamp = row[0]
  4.                 rx_max = row[1]
  5.  
  6.                 ret = rrdtool.update(ds_file.rrd,'%s:%s' %(time_stamp,rx_max));
  7.  
  8.                 if ret:
  9.                        print rrdtool.error()
  10.  
  11.           i = i + 1

我的问题是,只要有重复的时间戳,脚本就会崩溃,因为rrdTool只允许每个时间戳有一个值。因此,我得到了这个错误
回溯(最近一次呼叫):
文件"rrdfile_update.py",第40行,位于
RET=rrdtool.update(ds_file.rrd,'%s:%s'%(time_stamp,rx_max));
RrdTOOL.ERROR:DS_FILE:非法尝试使用时间1363358441进行更新,而上次更新时间为1363358441(至少一秒)
如果您能帮助我使用一条PythonTry Catch语句来帮助跳过这个错误,并使用下一个时间戳和值继续更新RRD文件,这样脚本就不会停止,我将非常感激。
非常感谢您的帮助。谢谢

# 回答1


Try/Except块可以通过执行以下操作来捕获任何错误:

选择 | 换行 | 行号
  1. try:
  2.     ...code that may raise an exception...
  3. except Exception, e:
  4.     print e

通常,最好通过检查来捕获特定的错误,如:

选择 | 换行 | 行号
  1. try:
  2.     ...code that may raise an exception...
  3. except rrdtool.error, e:
  4.     print e

您还可以发出
经过
语句,而不是打印错误

# 回答2


嗨,bvdet
非常感谢你的回答,它起作用了,这是我的最终代码
希望它也能帮助其他人

选择 | 换行 | 行号
  1. for i in range(numrowed):
  2.                 row = curred.fetchone()
  3.                 time_stamp = row[0]
  4.                 rx_max = row[1]
  5.                 try:
  6.                     ret = rrdtool.update(ds_file.rrd,'%s:%s' %(time_stamp,rx_max));
  7.                 except rrdtool.error, e:
  8.                     print e
  9.           i = i + 1
  10.  
  11.  
  12.  
# 回答3


假设您只想使用第一个时间戳,则构造一个包含已处理的时间集的集合,并对照它进行检查。

选择 | 换行 | 行号
  1. all_times = set()
  2. for i in range(numrowed):
  3.     row = curred.fetchone()
  4.     time_stamp = row[0]
  5.     rx_max = row[1]
  6.  
  7.     if time_stamp not in all_times:
  8.         ret = rrdtool.update(ds_file.rrd,'%s:%s' %(time_stamp,rx_max))
  9.         all_times.add(time_stamp) 

标签: python

添加新评论