[英]Python compile() function : get line number and last error message
我正在使用 compile function 来编译 python 字符串。 如何阅读编译错误的最后摘要以及错误的行号。
pystr = '''
print('abc')
print(abc)
'''
try:
compile(pystr, '', 'eval')
except Exception as e:
#print(e)
print(sys.exc_info())
######outputs##############
(<class 'SyntaxError'>, SyntaxError('invalid syntax', ('', 3, 'print(abc)\n')), <traceback object at 0x02BB7120>)
# I would need 1) last error message - 'SyntaxError: invalid syntax', 2) line number '3'.
我们可以使用下面的代码来读取 object e 的所有内容。 在那里我们会发现一些带有错误详细信息的属性:
pystr = '''
print('abc')
print(abc)
'''
try:
compile(pystr, '', 'eval')
except Exception as e:
# print all attributes
for attr in dir(e):
print("e.%s = %r" % (attr, getattr(e, attr)))
#useful attributes:
print(e.lineno)
print(e.msg)
print(e.text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.