我正在编写一个脚本,它将把来自asterisk系统的调用详细记录填充到MySQL日志数据库中。在下面的代码中,我试图忽略重复的键并继续下一行,但是当这段代码执行时,我看到的只是第一行重复警告,然后脚本退出(下面的示例2)。是否有一个明显的错误导致它失败?在
原谅我糟糕的Python礼节,我对这门语言很陌生。我的假设是,即使pass可能会突破异常,foreach循环也不会继续存在。在
编辑/注释:在我解决了退出for循环的问题之后,这一点也值得一提:因为我有一个finally:
块关闭了sql连接,finally:
块是在except: pass
之后执行的,并关闭了连接。所以在上面的例子中,finally:
仍然导致程序异常终止。在
#!/usr/bin/python -d
import csv
import sys
import MySQLdb as mdb
log="Master.csv"
try:
con = mdb.connect('1.2.3.4','abcd','efgh','ijkl')
cur = con.cursor()
#Inefficient way of getting row count.
rcount = csv.reader(open(log, 'rb'))
print "Number of rows in csv: %d" % (len(list(rcount)))
#OK, real csv processing now.
reader = csv.reader(open(log, 'rb'))
iter = 0
for row in reader:
print "Row: %d" % (++iter)
clid = row[0]
src = row[1]
dst = row[2]
dcontext = row[3]
channel = row[4]
dstchannel = row[5]
lastapp = row[6]
lastdata = row[7]
start = row[8]
end = row[10]
duration = row[11]
billsec = row[12]
disposition = row[13]
amaflags = row[14]
accountcode = row[15]
uniqueid = row[16]
insertstr= "INSERT INTO cdr_extended (duration,billsec,amaflags,start,end,clid,src,dst,dcontext,channel,dstchannel,lastapp,lastdata,disposition,accountcode,uniqueid) VALUES (%s,%s,0,'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s');" % (duration,billsec,start,end,clid,src,dst,dcontext,channel,dstchannel,lastapp,lastdata,disposition,accountcode,uniqueid)
cur.execute(insertstr)
con.commit()
except mdb.Error, e:
if e.args[0] == 1062:
print "Dupe key on uniqueid: %s" % (uniqueid)
pass
else:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
finally:
if con:
con.close()
输出:
^{pr2}$
pass
在python中被用来代替其他编程语言的空大括号。在if x>0: pass
等于}
c
的:if (x>0);
或{使用
continue
继续for循环。在仅将
try...except
块包装在导致异常的代码周围,该异常位于for
循环中。我不使用MySQLdb
,但类似这样的方法应该有效:相关问题 更多 >
编程相关推荐