Created
March 26, 2017 14:29
-
-
Save Hanaasagi/1c0e3430d6d2c9f5d6d109b2d861d497 to your computer and use it in GitHub Desktop.
捕捉异常并进行格式化输出
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import inspect | |
import textwrap | |
def error(): | |
raise ZeroDivisionError | |
try: | |
error() | |
except: | |
etype, evalue, etb = sys.exc_info() | |
info = inspect.getframeinfo(etb.tb_next, context=3) | |
lines = info.code_context | |
firstlineno = info.lineno - info.index | |
fmt = '<{}'.format(len(str(firstlineno+ len(lines)))) | |
msg = '>! {etype} at {filename}:{lineno}'.format(fmt=fmt, | |
etype=etype, filename=info.filename, lineno=info.lineno) | |
print(msg) | |
lines = textwrap.dedent(''.join(lines)) | |
for i, line in enumerate(lines.split('\n')): | |
msg = '{lineno:{fmt}}{seq}\t{line}'.format( | |
fmt=fmt, lineno=firstlineno+i, | |
seq=('>' if i==info.index else ':'), line=line) | |
print(msg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment