Python compile() 函数:获取行号和最后一条错误消息

Python compile() function : get line number and last error message

我正在使用编译函数来编译一个 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'.

我们可以使用下面的代码读取对象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)