找到python代码发生异常的行号 [英] Locating the line number where an exception occurs in python code
本文介绍了找到python代码发生异常的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个与此相似的代码:
I have a code similar to this:
try:
if x:
statement1
statement2
statement3
elif y:
statement4
statement5
statement6
else:
raise
except:
statement7
在这里,我确信这个例外发生在如果x:
阻止,但我想知道在哪个语句如果x:
阻止异常发生。有没有办法得到异常发生的行号?
Here, I am sure that the exception occurs in If x:
block, but I would like to know in which statement of If x:
block the exception occurs. Is there a way to get the line number where the exception occurs?
请问,
推荐答案
这是什么:
try:
if x:
print 'before statement 1'
statement1
print 'before statement 2' #ecc. ecc.
statement2
statement3
elif y:
statement4
statement5
statement6
else:
raise
except:
statement7
这是一个简单的解决方法,但我建议使用调试器
this is the straightforward workaround but I suggest to use a debugger
甚至更好,使用sys模块:D
or even better, use the sys module :D
try:
if x:
print 'before statement 1'
statement1
print 'before statement 2' #ecc. ecc.
statement2
statement3
elif y:
statement4
statement5
statement6
else:
raise
except:
print sys.exc_traceback.tb_lineno
#this is the line number, but there are also other infos
这篇关于找到python代码发生异常的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文