要簡單地得到行號,您可以使用sys
,如果您想要更多,請嘗試traceback模塊。
import sys
try:
[][2]
except IndexError:
print 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno)
打印:
Error on line 3
Example from the traceback
module documentation:
import sys, traceback
def lumberjack():
bright_side_of_death()
def bright_side_of_death():
return tuple()[0]
try:
lumberjack()
except IndexError:
exc_type, exc_value, exc_traceback = sys.exc_info()
print "*** print_tb:"
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
print "*** print_exception:"
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=2, file=sys.stdout)
print "*** print_exc:"
traceback.print_exc()
print "*** format_exc, first and last line:"
formatted_lines = traceback.format_exc().splitlines()
print formatted_lines[0]
print formatted_lines[-1]
print "*** format_exception:"
print repr(traceback.format_exception(exc_type, exc_value,
exc_traceback))
print "*** extract_tb:"
print repr(traceback.extract_tb(exc_traceback))
print "*** format_tb:"
print repr(traceback.format_tb(exc_traceback))
print "*** tb_lineno:", exc_traceback.tb_lineno
見http://stackoverflow.com/questions/3702675 /打印的全向掃描功能於蟒蛇,沒有休止-的程序! –
https://docs.python.org/2/library/traceback.html#traceback-examples – osa
@JeCh答案看起來不錯。請接受一個。要接受它,請單擊答案旁邊的空白複選標記。 –